Swa*_*rtz 19 forms select ruby-on-rails simple-form
我正在使用simple_form gem来创建Rails表单. http://github.com/plataformatec/simple_form
一切都很好,除了如何创建分组选择框?无法在文档中或谷歌搜索中找到它.
dol*_*nko 88
这个问题已经过时了,但它仍然是"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 %>
小智 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>
希望这可以帮助.
| 归档时间: | 
 | 
| 查看次数: | 15546 次 | 
| 最近记录: |