rails选择标签选择值

对于下面给出的代码,我想保持选择框的值为传递的值。

但这不起作用:

@yrs =[2011,2010,2009,2008]
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,:selected=>2011) %>

请告诉我如何去做。

谢谢

lamrin asked 2019-10-08T12:09:05Z
3个解决方案
93 votes

卸下:selected=>零件。

句法:

options_for_select(@options, @selected_options)

用法:

options_for_select(1..5, 3)  # creates a range 1..5 , with 3 as selected by default
M Tariq Aziz answered 2019-10-08T12:09:32Z
30 votes
<%= select_tag "page_type", options_for_select(@page_type.collect{ |u| [u.data_name, u.id]}, :selected=>@page.page_type), {:class =>"select_combobox",:onchange=>"reset_form(this.id,'page_type_msg');"} %>

这对我有用:)

manish nautiyal answered 2019-10-08T12:09:57Z
5 votes

只是为了澄清@M Tariq Aziz答案:

您的代码应如下所示:

@yrs =[2011,2010,2009,2008]
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,2011) %>

选择标记的一般格式为:

<%= select_tag 'year', options_for_select(:collection, :selected) %>
harrya answered 2019-10-08T12:10:39Z
translate from https://stackoverflow.com:/questions/7347039/rails-select-tag-selected-value