Rails选择助手设置默认值 [英] Rails select helper setting default value

查看:100
本文介绍了Rails选择助手设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

控制器

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

查看

<%= 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>...

如何在具有文件夹的parent_id的选择助手中设置默认值? 我试过options_for_select(@parents,DEFAULT VALUE HERE),也:selected => VALUE在不同的地方,没有结果.请帮助

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

推荐答案

如果将文件夹对象传递给form_tag,则Rails应该自动计算出默认值.您也不需要使用options_for_select,因为select表单帮助程序带有一系列选项.

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

此外,如果使用RESTful路由,则在form_tag中指定URL是多余的.

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

这篇关于Rails选择助手设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆