问题
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
回答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.
回答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
来源:https://stackoverflow.com/questions/24726377/rails-select-helper-setting-default-value