Rails select helper - Default selected value, how?

Viewed 204728

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?

15 Answers

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) %>

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?

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}
<%= f.select :project_id, options_from_collection_for_select(@project_select,) %>

Mike Bethany's answer above worked to set a default value when a new record was being created and still have the value the user selected show in the edit form. However, I added a model validation and it would not let me submit the form. Here's what worked for me to have a model validation on the field and to show a default value as well as the value the user selected when in edit mode.

  <div class="field">
    <%= f.label :project_id, 'my project id', class: "control-label" %><br>
    <% if @work.new_record? %>
      <%= f.select :project_id, options_for_select([['Yes', true], ['No', false]], true), {}, required: true, class: "form-control" %><br>
    <% else %>
      <%= f.select :project_id, options_for_select([['Yes', true], ['No', false]], @work.project_id), {}, required: true, class: "form-control" %><br>
    <% end %>
  </div>

model validation

  validates :project_id, presence: true

This should work for you. It just passes {:value => params[:pid] } to the html_options variable.

<%= f.select :project_id, @project_select, {}, {:value => params[:pid] } %>
Related