8 May 2009 · About 1 minute read

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:

```ruby# Doesn’t retain value

<%= 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]’,

options_for_select([[’- 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)

Chris Blunt
Chris Blunt @cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.