Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 983
totocaster Avatar asked Mar 08 '09 11:03

totocaster


8 Answers

This should do it:

<%= f.select :project_id, @project_select, :selected => params[:pid] %>
like image 120
htanata Avatar answered Nov 15 '22 19:11

htanata


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

<%= f.select :project_id, options_for_select(..., @work.project_id) %>
like image 26
lynx Avatar answered Nov 15 '22 18:11

lynx


Rails 3.0.9

select options_for_select([value1, value2, value3], default)
like image 58
Cheng Avatar answered Nov 15 '22 19:11

Cheng


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.

like image 41
Mike Bethany Avatar answered Nov 15 '22 18:11

Mike Bethany


Try this:

    <%= f.select :project_id, @project_select, :selected => f.object.project_id %>
like image 24
gavit Avatar answered Nov 15 '22 18:11

gavit


if params[:pid] is a string, which if it came from a form, it is, you'll probably need to use

params[:pid].to_i  

for the correct item to be selected in the select list

like image 11
danengle Avatar answered Nov 15 '22 18:11

danengle


I've found solution and I found that I'm pretty unexperienced in RoR.

Inside the controller that manages view described above add this:

@work.project_id = params[:pid] unless params[:pid].nil?
like image 10
totocaster Avatar answered Nov 15 '22 19:11

totocaster


<%= f.select :project_id, @project_select, :selected => params[:pid] %>
like image 7
jschorr Avatar answered Nov 15 '22 18:11

jschorr