Rails: Retaining select_tag's Selected Option

Working with Rails' select_tag helper to build a search form, I needed to retain the user's selected value after a form get, and was using the options_for_select helper:

<%= select_tag 'search[status]',

options_for_select([['- All -', nil]] + Settings[:states].collect { |name, id| [name.to_s.titlecase, id] },

params[:search][:status]) %>```


Whenever the form was posted, the select popup would always revert to its default value.


The reason? params[:search][:status] is by default a `String`, whereas the `option` values are integers, and so don't match ("1" != 1). The simple fix is to convert it to an integer using `to_i`:

ruby# Convert the given params[:search][:status] to an integer using to_i

<%= select_tag 'search[status]',

optionsforselect([['- All -', nil]] + Settings[:states].collect { |name, id| [name.to_s.titlecase, id] },

params[:search][:status].to_i) %>```

Update: Fixed missing bracket in code (25 May 2009)