user3581552
user3581552

Reputation: 85

Rails select helper setting default value

Controller

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

View

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

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

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

Upvotes: 0

Views: 862

Answers (2)

Arctodus
Arctodus

Reputation: 5847

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.

Upvotes: 1

Simone Carletti
Simone Carletti

Reputation: 176402

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

Upvotes: 0

Related Questions