rails select_tag选中的值

lam*_*rin 60 ruby-on-rails

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

但这不起作用:

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

请告诉我如何去做.

谢谢

小智 96

删除:selected=> 部分.

句法:

options_for_select(@options, @selected_options)
Run Code Online (Sandbox Code Playgroud)

用法:

options_for_select(1..5, 3)  # creates a range 1..5 , with 3 as selected by default
Run Code Online (Sandbox Code Playgroud)


man*_*yal 30

<%= 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');"} %>
Run Code Online (Sandbox Code Playgroud)

这对我有用:)


har*_*rya 5

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

您的代码应如下所示:

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

select标签的一般格式是:

<%= select_tag 'year', options_for_select(:collection, :selected) %>
Run Code Online (Sandbox Code Playgroud)