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
Use the right attribute of the current instance (e.g. @work.project_id
):
<%= f.select :project_id, options_for_select(..., @work.project_id) %>
This should do it:
<%= f.select :project_id, @project_select, :selected => params[:pid] %>
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.
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?
I couldn't get this to work and found that I needed to add the "selected" html attribute not only to the correct <option>
tag but also to the <select>
tag. MDN's docs on the selected attribute of the select tag say:
selected - Boolean attribute indicates that a specific option can be initially selected.
That means the code should look like:
f.select :project_id, options_for_select(@project_select, default_val), html: {selected: true}
If try to print the f object, then you will see that there is f.object that can be probed for getting the selected item (applicable for all rails version > 2.3)
logger.warn("f #{f.object.inspect}")
so, use the following script to get the proper selected option:
:selected => f.object.your_field