如何使用simple_form创建分组选择框?

我正在使用simple_form gem来创建Rails表单。 http://github.com/plataformatec/simple_form

一切都很好,除了如何创建分组选择框? 无法在文档中或谷歌搜索中找到它。

这个问题已经过时了,但它仍然是“simple_form分组选择”google搜索的最佳结果,所以我认为下一位读者可能会受益于一些创造性的方法来创建这些最新的simple_form(取自测试,这些测试总是最好的文档)

<%= f.input :author, :as => :grouped_select, :collection => [['Authors', ['Jose', 'Carlos']], ['General', ['Bob', 'John']]], :group_method => :last %> <%= f.input :author, :as => :grouped_select, :collection => Proc.new { [['Authors', ['Jose', 'Carlos']], ['General', ['Bob', 'John']]] }, :group_method => :last %> <%= f.input :author, :as => :grouped_select, :collection => { ['Jose', 'Carlos'] => 'Authors' }, :group_method => :first, :group_label_method => :last %> <%= f.input :author, :as => :grouped_select, :collection => { 'Authors' => ['Jose', 'Carlos'] }, :group_method => :last, :label_method => :upcase, :value_method => :downcase %> 

如果你有两个类别的子模型,子类别如下:

 class Category < ActiveRecord::Base has_many :products has_many :subcategories end class Subcategory < ActiveRecord::Base belongs_to :category has_many :products end 

然后你可以使用

 <%= simple_form_for [:admin, @yourmodel] do |f| %> <%= f.input :subcategory_id, collection: Category.all, as: :grouped_select, group_method: :subcategories, prompt: "Select One" %> <%= f.submit "Submit" %> <% end %> 

结果是这样的:

 

希望这可以帮助。

我发现创建分组选择框的唯一方法是使用传递在allocation_options_for_select中的select帮助器 ,它确实为choices参数选择了selected_key参数(因此您可以确保模型中设置的那个实际被选中)。 你会在下面看到完整的电话。 对不起,如果它令人困惑。

 -# @answer is the model instance passed into simple_form_for/form_for select(@answer.class.to_s.underscore, :question_id, option_groups_from_collection_for_select(@categories, 'questions.order(:display_order)', :name, :id, :question, @answer.question_id)) 

如果有更好的方法来选择合适的值,我也都是耳朵。

tl; dr: nope没有看到任何forms的form_for或simple_form_for创建分组选择,上面应该至少有帮助。

我刚刚看了一下这些测试。 如果要将不同的值传递给选项标记,请使用以下命令将其传递给集合:

 Agent = Struct.new(:id, :name) agents = [["First", []], ["Second", [Agent.new(7, 'Bond'), Agent.new(47, 'Hitman')]]] 

请参阅https://github.com/plataformatec/simple_form/blob/master/test/inputs/grouped_collection_select_input_test.rbu