Rails:在ActionView-Helper'collection_select'中预先选择一个值 [英] Rails: Preselect a value in ActionView-Helper 'collection_select'

查看:79
本文介绍了Rails:在ActionView-Helper'collection_select'中预先选择一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 ActionView帮助器collection_select 取一个将在下拉菜单中预先选择的值.

I'm trying to get the ActionView-Helper collection_select to take a value that will be preselected in the dropdown-menu.

都不是(html-option-hash中的:selected)

Neither (:selected in the html-option-hash)

<%= collection_select(:my_object, :my_method, @my_collection, :id, :description_string, {}, {:selected => @my_collection_object.id}) %>

也(选项哈希中的:selected)

<%= collection_select(:my_object, :my_method, @my_collection, :id, :description_string, {:selected => @my_collection_object.id}, {}) %>

似乎可以工作.

我做错了什么?有人可以帮我吗?

What am I doing wrong? Can anyone help me on this one?

推荐答案

来自样本使用情况(为Post@post的实例选择关联的Author):

Sample usage (selecting the associated Author for an instance of Post, @post):

collection_select(:post, :author_id, Author.all, :id, :name_with_initial)

如果@post.author_id已经为1,则返回:

If @post.author_id is already 1, this would return:

<select name="post[author_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">D. Heinemeier Hansson</option>
  <option value="2">D. Thomas</option>
  <option value="3">M. Clark</option>
</select>

因此,您只需要确保@my_object.my_method返回的值与可用选项值之一匹配即可.如果存在匹配项,则将选择该选项.

So you just need to make sure that @my_object.my_method returns a value that matches one of the available option values. If there's a match then that option will be selected.

这篇关于Rails:在ActionView-Helper'collection_select'中预先选择一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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