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?
This should do it:
<%= f.select :project_id, @project_select, :selected => params[:pid] %>
Use the right attribute of the current instance (e.g. @work.project_id
):
<%= f.select :project_id, options_for_select(..., @work.project_id) %>
Rails 3.0.9
select options_for_select([value1, value2, value3], default)
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.
Try this:
<%= f.select :project_id, @project_select, :selected => f.object.project_id %>
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
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?
<%= f.select :project_id, @project_select, :selected => params[:pid] %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With