Rails:在 ActionView-Helper“collection_select”中预选择一个值
我正在尝试获取 ActionView-Helper collection_select
获取将在下拉菜单中预先选择的值。
(:selected
in the html-option-hash)
<%= collection_select(:my_object, :my_method, @my_collection, :id, :description_string, {}, {:selected => @my_collection_object.id}) %>
和 (:selected
in the option-hash)
<%= collection_select(:my_object, :my_method, @my_collection, :id, :description_string, {:selected => @my_collection_object.id}, {}) %>
似乎都不起作用。
我究竟做错了什么? 有人能帮我解决这个问题吗?
I'm trying to get the ActionView-Helper collection_select
to take a value that will be preselected in the dropdown-menu.
Neither (:selected
in the html-option-hash)
<%= collection_select(:my_object, :my_method, @my_collection, :id, :description_string, {}, {:selected => @my_collection_object.id}) %>
nor (:selected
in the option-hash)
<%= collection_select(:my_object, :my_method, @my_collection, :id, :description_string, {:selected => @my_collection_object.id}, {}) %>
seem to work.
What am I doing wrong? Can anyone help me on this one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
来自 docs:
示例用法(选择关联的
,Post
实例的 Author@post
):如果
@post.author_id
已经是 1,则将返回:您只需确保
@my_object.my_method
返回与可用选项值之一匹配的值。 如果存在匹配,则将选择该选项。From the docs:
Sample usage (selecting the associated
Author
for an instance ofPost
,@post
):If
@post.author_id
is already 1, this would return: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.根据 文档,如果
@my_object. my_method
与其中一个选项具有相同的值,默认情况下将选择该选项。相反,您可以尝试使用
options_from_collection_for_select
与select_tag
:According to the docs, if
@my_object.my_method
has the same value as one of the options, that one will be selected by default.Conversely, you could try using
options_from_collection_for_select
in conjunction withselect_tag
:使用
:selected_value
Use
:selected_value
检查 @my_object.my_method 是否返回 nil。 如果是的话,
除此之外,您可以尝试使用 lambda,就像在 rdoc 示例中那样
在您的情况下,这看起来像
Check if @my_object.my_method returns nil. If it does,
Other than that, you can try using lambda, like in the rdoc example
In your case this will look like
如果您的集合采用 2 值数组的形式,它也适用:
:first
和:last
技巧对于这些事情非常有效,而不必为他们定义一个单独的模型。It also works if your collection is in the form of an array of 2-value arrays:
The
:first
and:last
trick works quite nicely for these things, without having to define a separate model for them.