2014-02-17 69 views
1

我試圖將select tag的默認值設置爲saved in the model in active record的值。同時,如果未指定任何值(例如在模型創建時),我想要顯示list以選擇選擇標記的某個字段。選擇標記+活動記錄的Rails默認值

這是我想做到這一點:

<% valid_years = Array.new %> 
<% for i in 1900..Time.now.year %> 
<% valid_years << i %> 
<% end %> 
<%= f.label t :label_year_of_birth %> 
<%= f.select :year_of_birth, options_for_select(valid_years), class: "" %> 

然而,這是保存在活動記錄的值在此選擇標籤not displayed。而是顯示數組的第一個值。另外,如果我寫options_for_select(valid_years, 1950),rails將不會將該值設置爲1950.

但是,如果我使用簡單的text field tag,rails會將保存的值放入其中。

<%= f.label t :label_year_of_birth %> 
<%= f.text_field :year_of_birth, class: "" %> 

回答

2

更換

<%= f.select :year_of_birth, options_for_select(valid_years), class: "" %> 

隨着

<%= f.select :year_of_birth, options_for_select(valid_years, form_for_object_name.year_of_birth), class: "" %> 

其中 form_for_object_name是要傳遞到您的形式,因爲你不同意<%= form_for(?) do |f| %>的對象。

options_for_select取第二個參數,即form_for_object_name.year_of_birth作爲selected的值。 如果form_for_object_name.year_of_birth爲零,則選擇將默認爲您的選項的第一個值,即1900

+0

謝謝!完全忘記了這一點。曾經使用過一次:P – JustBasti