如何使用simple_form创建分组的选择框?
-
26-09-2019 - |
题
我使用simple_form宝石用于创建Rails的形式。 http://github.com/plataformatec/simple_form
所有是伟大的,除了我如何创建分组的选择框?找不到它在文档或谷歌-ING。
解决方案
现在的问题是旧的,但它是顶部的结果“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 %>
其导致这样的:
<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>
希望这有助于。
只有我发现创建分组选择框理智的方法是使用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:强>都能跟得上没有看到与任一任何方式的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 /斑点/主/测试/输入/ grouped_collection_select_input_test.rb
不隶属于 StackOverflow