2011-04-10 41 views
3

我有這個在我的模型:select_tag傭工grouped_options_for_select爲了

LOCATION_IN_UK = {'England' => [['Berkshire', 1],['Cambridgeshire',2],['Cheshire',3]], 'Scotland' => [['Dumfries and Galloway',4],['Fife',5],['Lothian',6]], 'Others' => [['Outside UK',7]]} 

而且這是在視圖:

<%= select_tag :location, grouped_options_for_select(Location::LOCATION_IN_UK), :id => 'location-dropdown' %> 

此代碼生成以下HTML:

<select id="location-dropdown" name="location"> 
    <optgroup label="England"> 
    <option value="1">Berkshire</option> 
    <option value="2">Cambridgeshire</option> 
    <option value="3">Cheshire</option></optgroup> 
    <optgroup label="Others"> 
    <option value="7">Outside UK</option></optgroup> 
    <optgroup label="Scotland"> 
    <option value="4">Dumfries and Galloway</option> 
    <option value="5">Fife</option> 
    <option value="6">Lothian</option></optgroup> 
</select> 

1.如何跳過字母排序順序。我希望元素的位置完全在散列LOCATION_IN_UK中。
2.如何向此插入提示? :prompt => 'Please select'不起作用

回答

11

要回答您的提示問題,提示不是散列,它是方法調用的第三個參數。所以你會這樣做:

<%= select_tag :location, grouped_options_for_select(LOCATIONS_IN_UK, nil, "Please Select"), :id => 'location-dropdown' %> 

而在看源代碼,似乎沒有辦法跳過排序。儘管如此,你可以編寫自己的幫助器方法。這裏是源

# File actionpack/lib/action_view/helpers/form_options_helper.rb, line 449 
     def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil) 
     body = '' 
     body << content_tag(:option, prompt, { :value => "" }, true) if prompt 

     grouped_options = grouped_options.sort if grouped_options.is_a?(Hash) 

     grouped_options.each do |group| 
      body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0]) 
     end 

     body.html_safe 
     end 

您可以修改/重寫方法,但如果你在其它地方使用此功能,這就是爲什麼我建議你把你的application_helper以下是可能會斷裂。

def unsorted_grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil) 
    body = '' 
    body << content_tag(:option, prompt, { :value => "" }, true) if prompt 

    ##Remove sort 
    #grouped_options = grouped_options.sort if grouped_options.is_a?(Hash) 

    grouped_options.each do |group| 
    body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0]) 
    end 

    body.html_safe 
end 

你可以調用unsorted_grouped_options_for_select,它應該工作。

<%= select_tag :location, unsorted_grouped_options_for_select(LOCATION::LOCATION_IN_UK, nil, "Please Select"), :id => 'location-dropdown' %> 
+0

對不起,這是行不通的。說錯誤的參數數量(2個3)給我。我嘗試刪除零,所有的工作,但提示選項不會出現 – 2011-04-10 14:24:17

+0

你在什麼版本的軌道?另外,看看我的編輯,如果你使用我的第二個功能,那麼它應該工作。 – Gazler 2011-04-10 14:26:20

+0

看起來像提示不適用於select_tag,我將它包裝到一個窗體中,並調用爲f.select,現在工作正常。去看看訂單問題。謝謝! – 2011-04-10 14:30:41