Selected attribute in options_for_select

Hello Everyone

I have a select_tag which I populate using a map, I use
options_for_select method to pass the map and “selected” value. For some
reason I can not get the option “selected” based on the value I pass to
the selected attribute. Here is the code

<%= select_tag :current_course,
options_for_select( Course.find(:all).map {|p| [p.title,p.id]},
@selected )
%>

The corresponding HTML produced is

Mathematics I Engineering Design Technical Writing

When I printed the value of @selected variable, it is either 1,2 or 3.
But I never get any option selected.

Interestingly if instead of passing @selected, I pass 1, 2 or 3 as in
the code below

<%= select_tag :current_course,
options_for_select( Course.find(:all).map {|p| [p.title,p.id]},
2 )
%>

I DO GET 2nd option selected.

I am wondering, if I am doing anything wrong passing a variable as
“selected” attributed in options_for_select method.

Any help or suggestions would really be appreciated.

Thanks

  • AJ

the @selected value needs to be an integer to match the integer in the
option value.
‘to_i’ is your friend here.

<%= select_tag :current_course,
options_for_select( Course.find(:all).map {|p|
[p.title,p.id]},
@selected.to_i )
%>

Word.

  • dhj

On Jul 20, 6:25 pm, Abhishek J. [email protected]

Jeff Emminger wrote:

likely @selected is a different type than p.id, i.e. not an int.

try

<%= select_tag :current_course,
options_for_select( Course.find(:all).map {|p|
[p.title,p.id]},
@selected.to_i )
%>

On Jul 20, 6:25�pm, Abhishek J. [email protected]

to_i did work.

Thanks guys

-AJ

likely @selected is a different type than p.id, i.e. not an int.

try

<%= select_tag :current_course,
options_for_select( Course.find(:all).map {|p|
[p.title,p.id]},
@selected.to_i )
%>

On Jul 20, 6:25 pm, Abhishek J. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs