Ruby on Rails-f.s中的多项选择

我的表单中有以下选择框:

Related Type: &nbsp; <%= f.select(:TYPE, [['Type A', 'Type A'],
                                  ['Type B', 'Type B'],
                                  ['Type C', 'Type C'],
                                  ['Type D', 'Type D'],
                                  ['Type E', 'Type E']
                                 ],{ :prompt => "Please select"}
                                 ) %>

我想允许用户进行多个选择,并选择框5的大小。

上面的代码该怎么做?

Kim asked 2020-01-13T02:09:43Z
5个解决方案
78 votes

在您的:prompt之后,添加另一个带有html选项的哈希,例如

<%= f.select(:TYPE, [['Type A', 'Type A'],
                                  ['Type B', 'Type B'],
                                  ['Type C', 'Type C'],
                                  ['Type D', 'Type D'],
                                  ['Type E', 'Type E']
                                 ],{ :prompt => "Please select"},
                                   { :multiple => true, :size => 5 }
                                 ) %>

完成此操作后,您可能需要移动:prompt选项(不过请保留为空的{},以便html属性不会被视为Rails选项。)

另外,您还需要确保控制器代码正确地接受和处理多个值。

mikej answered 2020-01-13T02:10:10Z
9 votes

如果要收款,请尝试

    <%= f.select(:TYPE, Categories.collect {|p| [ p.name, p.id ] }, 
                                           { :prompt => "Please select"}, 
                                           { :multiple => true, :size => 5 }) %>
Swathi answered 2020-01-13T02:10:30Z
8 votes

在以下情况下,我有一个完整的示例(包括在编辑对象时进行预选择):

  • Object.rb是考虑的对象
  • Object.rb是建立关系的关键,也是string

形式:

form_for(@object) do |f|
  = f.select :similar_ids, options_from_collection_for_select(Object.all, :id, :name, {:selected => @object.similar_ids.split(';')}), {}, {:multiple => true, :size => 4, :name => 'object[similar_ids][]'}

Object.rb模型中:

class Object < ActiveRecord::Base
  before_save :handle_similars

  def handle_similars
    self.similar_ids = self.similar_ids.select(&:present?).join(';') 
    # .select(&:present?) is necessary to avoid empty objects to be stored
  end

  def similars
    self.class.find(self.similar_ids.split(';'))
  end

end

这些帖子帮助我:

  • 选择带有多个预选值的标签-在数据库中手动插入值
  • Ruby on Rails:以表单提交数组

希望能帮助到你

Augustin Riedinger answered 2020-01-13T02:11:25Z
2 votes

的HTML

<%= form.select(:product_ids, Product.all.collect {|p| [ p.name, p.id ] }, 
                                                   { :prompt => "Please select"}, 
                                                   { :multiple => true, :size => 5  }) %>

控制者

@category = Category.new(category_params) 

def category_params
    params.require(:category).permit(:name, product_ids: [])
end
Sanjay Choudhary answered 2020-01-13T02:11:49Z
0 votes

{:prompt =>“ Please select”},{:multiple => true,:size => 5} {}在f.select很重要

ysk answered 2020-01-13T02:12:09Z
translate from https://stackoverflow.com:/questions/4864513/ruby-on-rails-multiple-selection-in-f-select