如何为f.select表单字段设置空白值 [英] How do I set a blank value for an f.select form field

查看:192
本文介绍了如何为f.select表单字段设置空白值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下内容允许我的用户在其个人资料中选择自己的性别.

I am using the following to allow my users to select their sex in their profile.

<%= f.select (:sex, %w{ Male Female }) %>

如果未将任何内容传递给user.sex列,我将如何创建该列表默认的空白值?我只是通过男性或女性作为字符串.

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.

推荐答案

有两种可能,具体取决于您所追求的目标:

There are two possibilities, depending on what you're after:

<%= f.select (:sex, %w{ Male Female }, :include_blank => true) %>

这将始终在选择项中包含一个空白选项,如果人们在编辑表单上看到此值,则可以将其设置回空白值.

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.

<%= f.select (:sex, %w{ Male Female }, :prompt => "Gender...") %>

这将包括指定的提示值,只要尚未设置该字段.如果有(例如,在编辑表单上),则无需提醒用户他们需要选择一个值,从而不会出现提示

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

这篇关于如何为f.select表单字段设置空白值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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