Ruby on Rails:如何在 select_tag 中使用默认占位符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4557701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails: how do I use a default placeholder thing in a select_tag?
提问by NullVoxPopuli
<%= select_tag(:services,
options_from_collection_for_select(Service.all, :id, :name))%>
And it displays all the services...
它显示所有服务...
But I want it to be something like:
但我希望它是这样的:
Select a service
Service1
Service2
Service3
Service4
采纳答案by Zabba
<%= select_tag(:services,
Service.all.collect { |c| [c.id, c.name] }.
insert(0, "Select a Service"))%>
As answered for the question, this is for Rails 2.3. For Rails 3, see Prathan Thananart's answer.
正如对问题的回答,这是针对 Rails 2.3 的。对于 Rails 3,请参阅 Prathan Thananart 的回答。
回答by Prathan Thananart
Most of the time, you don't want to append anything to the array directly; either of these is a cleaner solution:
大多数情况下,您不想直接向数组追加任何内容;其中任何一个都是更清洁的解决方案:
- Use
:prompt => "Placeholder"if you want the placeholder to show up only when the attribute is nil at the time the form is rendered. It will be selected by default, but nothing will be saved if user submits. If the attribute is already populated [possibly because a) there's a default value or b) it's an edit form], the placeholder item will be omitted from the list entirely. - Use
:include_blank => "Placeholder"if you want to include the placeholder in the rendered list at all times.
- 使用
:prompt => "Placeholder",如果你想占位符展现出来,只有当属性是零的形式呈现的时间。它将默认选中,但如果用户提交,则不会保存任何内容。如果属性已经填充[可能是因为 a) 有一个默认值或 b) 它是一个编辑表单],占位符项将从列表中完全省略。 :include_blank => "Placeholder"如果要始终在渲染列表中包含占位符,请使用。
回答by Will
The better way to do this would be to use the :prompt parameter. Something like:
更好的方法是使用 :prompt 参数。就像是:
select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:prompt => 'Select Person'})
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

