我使用simple_form gem創建Rails窗體。 http://github.com/plataformatec/simple_form如何使用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