[Solved] Rails select helper setting default value


def edit
@folder = Folder.find(params[:id])
@parents = Folder.all.where(:user_id => current_user).map{|u| [ u.name, u.id ]}


<%= form_for(:folder, :url => {:action => 'update', :id => @folder.id}) do |f| %>

    <table summary="Folder form fields">
        <td><%= f.text_field(:name) %></td>
        <th>Parent folder:</th>
        <%= f.select(:parent_id, options_for_select(@parents) )%></td>

How to set a default value in select helper with a folder’s parent_id ?
I’ve tried options_for_select(@parents, DEFAULT VALUE HERE) , also :selected => VALUE in a different places, no result. Please help

Solution #1:

If you pass the folder object to form_tag then Rails should work out the default value automatically. You also shouldnt need to use options_for_select as the select form helper takes an array of options.

<%= form_for(@folder, :url => {:action => 'update', :id => @folder.id}) do |f| %>
  <%= f.select(:parent_id, @parents) %>
<% end %>

Also, specifying the URL in form_tag is redundant if you use RESTful routes.

Respondent: Sharagoz

Solution #2:

In a form_for, the default value is the value assigned to the object the form is built on. That means if you want the select to default to certain value, you need to set the parent_id attribute in the controller to that value.

@folder.parent_id = 23 # the default value
Respondent: Simone Carletti

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.