如何使用simple_form创建分组选择框?
我使用simple_form gem创建Rails窗体。 http://github.com/plataformatec/simple_form如何使用simple_form创建分组选择框?
一切都很好,除了我如何创建一个分组选择框?找不到文档或通过谷歌。我发现创建分组选择框
问题是旧的,但它是“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 %>
唯一明智的方法是使用select助手传递一个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: nope没有看到form_for或simple_form_for以创建分组选择的任何方式,上面应该至少有所帮助。
如果哈瓦两款车型都是哪些类别,子类别如下:
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>
希望这有助于。
哦..天啊。你先生,这是一个奇迹。我刚刚花了最后一个小时在一起玩一些东西,以获得一个阵列,在阵列中......按照选定的答案。然后我看到了你的解释,我在20秒内重复了这一点。非常感谢。我完全倒退了。 – Tim 2015-10-22 21:44:14
我只是看了一下测试。 如果你想一个不同的值传递给选项标签,使用下面的方法将它传递到集合:
Agent = Struct.new(:id, :name)
agents = [["First", []], ["Second", [Agent.new(7, 'Bond'), Agent.new(47, 'Hitman')]]]
分组选择框已被添加到simple_form 2.0。 – Shreyas 2012-03-26 09:09:40