Month: October 2014

Rails 2.3 and options_for_select

I spent half a day on Tuesday trying to debug the following:

<%= f.select :number_of_items, options_for_select([1,2,3,4,5], @number_of_items), {}, {:class => "OrderField"} %>

Here, @number_of_items is the value of the same selection list, if for some reason the user had erroneously entered something in the rest of the form.

Turns out what happens is that the value is returned from the form and then assigned to @number_of_items is a string. Options_for_select throws an error because it is trying to create a selection list with integers as values, but is being told to set a string as the default value.

The form will keep loading up without the default value selected and you’ll waste hours wondering what’s wrong.

Solution: Do some type conversion like so:
<%= f.select :number_of_items, options_for_select([1,2,3,4,5], @number_of_items.to_i), {}, {:class => "OrderField"} %>

..Yup.