2010-10-27 28 views

回答

80

問題是舊的,但它是「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 %> 
+0

現貨。感謝您提供幾種不同的解決方案我希望他接受你的答案。 – Eytan 2012-10-24 16:09:47

+0

我假設這是爲了simple_form 2.0+?或者,這將與舊的simple_form一起使用,就像我在2010年嘗試使用的一樣。 – Swartz 2012-11-05 08:01:31

+1

現金貨幣!第一種解決方案對我來說非常合適。非常感謝! – 2013-06-04 21:33:17

0

唯一明智的方法是使用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以創建分組選擇的任何方式,上面應該至少有所幫助。

6

如果哈瓦兩款車型都是哪些類別,子類別如下:

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> 

希望這有助於。

+0

哦..天啊。你先生,這是一個奇蹟。我剛剛花了最後一個小時在一起玩一些東西,以獲得一個陣列,在陣列中......按照選定的答案。然後我看到了你的解釋,我在20秒內重複了這一點。非常感謝。我完全倒退了。 – Tim 2015-10-22 21:44:14

相關問題