2012-07-27 63 views
20

下面是我的選擇表單,它可以正常工作。如何將'select one ...'添加到options_from_collection_for_select

當用戶加載頁面時,它應該顯示一個初始'select one ...',其值爲null或''。

我試圖將它添加到對象,但無法並且很樂意獲得幫助!

非常感謝!


筆者認爲:

= select_tag 'incident[fault_id]' , options_from_collection_for_select(Fault.all, :id, :label) 

我使用的Rails 3.2和HAML


更新:

一次偶然的機會我發現了一些真甜:

include_blank: 'select one...' 

或完全

= f.collection_select :fault_id, Fault.order(:label), :id, :label, include_blank: 'select one...' 

如果一個喜歡太...

參考:http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

+0

您可以將您的「內聯」答案移至問題的真實答案,以便人們可以投票支持。不幸的是:include_blank或:prompt只能用於rails 3.x + – rogerdpack 2014-12-07 06:20:29

回答

38

options_from_collection_for_select返回選項標籤的字符串已被遍歷編譯將值調用的結果作爲選項值並將text_method作爲選項文本分配給value_method。

所以只是 「select_one」 選項字符串前面加上它沒有價值:

= select_tag 'incident[fault_id]', content_tag(:option,'select one...',:value=>"")+options_from_collection_for_select(Fault.all, :id, :label) 
+0

非常感謝!這很容易,如果你知道它... – 2012-07-27 13:13:40

+1

甜終於一個選項,與鋼筋2.x與3.x使用:include_blank或什麼不相信... – rogerdpack 2014-12-07 06:20:55

+1

雖然這工作,它會更正確的使用'提示'選項,如下所述。 – 2015-05-12 06:21:22

19

:promptselect_tagoptions_from_collect_for_select一個屬性,以便

select_tag("sales_rep[manufacturer_id]", options_from_collection_for_select(@manufacturers, "id", "name"), { :prompt => 'Select Manufacturer' }) 
0

你可以嘗試以下方法:

collection_select(:sales_rep, :manufacturer_id, @manufacturers, :id, :name, { :prompt => 'Select Manufacturer' }) 
相關問題