20

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

一切都很好,除了如何创建分组选择框?在文档中或通过 google-ing 找不到它。

4

4 回答 4

94

这个问题很老,但无论如何它是“simple_form grouped select”谷歌搜索的最佳结果,所以我认为下一位读者可能会受益于一些创造性的方法来使用最新的 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 %>
于 2012-06-14T11:37:08.540 回答
8

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

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>

希望这可以帮助。

于 2015-03-31T15:01:25.443 回答
0

我发现创建分组选择框的唯一合理方法是使用传递grouped_options_for_select的选择助手,它确实为选择参数采用 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:没有看到任何使用 form_for 或 simple_form_for 创建分组选择的方法,以上内容至少应该有所帮助。

于 2010-12-02T18:59:31.677 回答
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

于 2016-03-10T16:31:05.603 回答