2011-09-08 10 views
47

以下のコードでは、選択したボックスを渡された値のままにしたかったのです。rails select_tag選択された値

しかし、これは動作しません:

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

は、どのようにそれについて移動する私に教えてください。

おかげ

+0

:)私の作品に動作し、それを受け入れてください。 –

答えて

82

:selected=>部分を削除します。

構文:

options_for_select(@options, @selected_options) 

用途:

options_for_select(1..5, 3) # creates a range 1..5 , with 3 as selected by default 
5

だけ明確にする@Mタリク・アジズ答え:

あなたのコードは次のようになります。

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

selectタグのための一般的な形式は次のとおりです。

<%= select_tag 'year', options_for_select(:collection, :selected) %> 
+1

私は選択された値として文字列を使用していたので、キー値として整数を持っていました。あなたがto_aを使用した場所では、to_iを使用する必要がありました。正しい方向に私を指してくれてありがとう。これは私のために働いた:<%= select_tag(:map_set_priority_filter、options_for_select(MapSet.priority_filters.collect {| priority | [priority.name、priority.id]}、@ map_set_priority_filter.to_i))%> – John

25
<%= 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');"} %> 

これは@Mタリク・アジズが提供する答えた場合は、

関連する問題