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

时间:2010-10-27 20:41:59

标签: ruby-on-rails forms select simple-form

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

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

4 个答案:

答案 0 :(得分:87)

这个问题已经很久了,但它是" simple_form分组选择"的最佳结果。谷歌搜索无论如何,所以我认为下一个读者可能会受益于一些创造性的方法来创建这些最新的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 %>

答案 1 :(得分:7)

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

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 %>

结果如下:

<div class="form-group grouped_select optional yourmodel_subcategory_id">
    <label class="grouped_select optional control-label" for="yourmodel_subcategory_id">Subcategory</label>
    <select class="grouped_select optional form-control" id="yourmodel_subcategory_id" name="yourmodel[subcategory_id]">
    <option value="">Select One</option>
    <optgroup label="Your 1st Category">
        <option value="This subcategory id">one subcategory belongs to Your 1st Category</option>
    </optgroup>
    <optgroup label="Your 2nd Category">
        <option value="This subcategory id">one subcategory belongs to Your 2nd Category</option>
    </optgroup>
    </select>
</div>

希望这有帮助。

答案 2 :(得分:0)

我发现创建分组选择框的唯一方法是使用传递grouped_options_for_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没有看到任何方式使用form_for或simple_form_for来创建分组选择,上面应该至少有帮助。

答案 3 :(得分:0)

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

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.rb