0

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

user3581552
  • 85
  • 1
  • 1
  • 7
  • Try `<%= f.select(:parent_id, options_for_select(@parents,@parents.project_id) )%>` – Pavan Jul 13 '14 at 19:26
  • 1
    possible duplicate of [Rails select helper - Default selected value, how?](http://stackoverflow.com/questions/623458/rails-select-helper-default-selected-value-how) – Pavan Jul 13 '14 at 19:28
  • I've checked that already, yours doesnt work. I need to bind that list with a current folder parent_id value – user3581552 Jul 13 '14 at 19:31
  • This one `<%= f.select(:parent_id, options_for_select(@parents),:selected => f.object.parent_id) %>`? – Pavan Jul 13 '14 at 19:34
  • Pavan you are the one who always give advices which are doesn't help ))) have you tested it by yourself ?)))) – user3581552 Jul 14 '14 at 11:34

2 Answers2

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.

Arctodus
  • 5,743
  • 3
  • 32
  • 44
0

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
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364