Rails select helper - Default selected value, how?

Here is a piece of code I'm using now:

<%= f.select :project_id, @project_select %>

How to modify it to make its default value equal to to params[:pid] when page is loaded?


Solution 1:

This should do it:

<%= f.select :project_id, @project_select, :selected => params[:pid] %>

Solution 2:

Use the right attribute of the current instance (e.g. @work.project_id):

<%= f.select :project_id, options_for_select(..., @work.project_id) %>

Solution 3:

Rails 3.0.9

select options_for_select([value1, value2, value3], default)

Solution 4:

The problem with all of these answers is they set the field to the default value even if you're trying to edit your record.

You need to set the default to your existing value and then only set it to the actual default if you don't have a value. Like so:

f.select :field, options_for_select(value_array, f.object.field || default_value)

For anyone not familiar with f.object.field you always use f.object then add your field name to the end of that.

Solution 5:

Try this:

    <%= f.select :project_id, @project_select, :selected => f.object.project_id %>