如何为 f.select 表单字段设置空白值
我使用以下内容允许我的用户在他们的个人资料中选择他们的性别。
<%= f.select (:sex, %w{ Male Female }) %>
如果没有任何内容传递到 user.sex 列,我将如何创建列表默认的空白值?我只是将男性或女性作为字符串传递。
目的是我想要一个空白值,以便验证可以确保他们知道必须选择它。
I am using the following to allow my users to select their sex in their profile.
<%= f.select (:sex, %w{ Male Female }) %>
How would I create a blank value that the list would default to if nothing has been passed to the user.sex column? I am simply passing male or female as a string.
The purpose is I want a blank value so a validation can make sure they are aware they have to select it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
有两种可能性,具体取决于您的需求:
include_blank
这将始终在选择中包含一个空白选项,这将允许人们在看到时将值设置回空白值这在编辑表单上。
prompt
只要该字段尚未设置,这将包括指定的提示值。如果有(例如在编辑表单上),则无需提醒用户他们需要选择一个值,这样提示就不会出现
There are two possibilities, depending on what you're after:
include_blank
This will always include a blank option in the select, which will allow people to set the value back to the blank value if they're seeing this on an edit form.
prompt
This will include the specified prompt value, so long as the field hasn't already been set. If it has (on an edit form for example), there's no need to remind the user that they need to select a value so the prompt doesn't appear
我认为你可以这样做:
I think you can do something like this:
在 Rails 4 中,您可以实现这样的提示:
它以简单的形式为我工作。
in Rails 4 you can achieve prompt like this:
its working for me with simple form.
你和
You go with
我尝试使用“提示”作为字符串。但在渲染的输出中,没有出现新选项提示。 select_tag 方法仅搜索符号。 :include_blank 似乎也是如此。查看 options.delete:
另请注意,:include_blank 和 :prompt 将是 select 或 select_tag 的选项,而不是 options_for_select 的选项。
I tried to use 'prompt' as a string. But in the rendered output, the new option prompt was not appearing. The select_tag method searches only for a symbol. It appears to be the case for :include_blank as well. Check out the options.delete:
Also note that :include_blank and :prompt will be options of the select or select_tag, not the options_for_select.