[英]How can I allow NULL values in a drop down list using Ruby on Rails?
Suppose I had a dropdown list in my form that allows users to select their favorite hot drink. 假设我的表单中有一个下拉列表,允许用户选择自己喜欢的热饮。
<%= form_for @person do |f| %>
<%= f.select :hot_drink, [['Tea', 'tea'], ['Coffee', 'Coffee']]
...
I want users to able to enter a NULL value if they don't like hot drinks. 我希望用户如果不喜欢喝热饮料,可以输入NULL值。 Something like this:
像这样:
<%= f.select :hot_drink, [['Nothing Selected', NULL], ['Tea', 'tea'], ['Coffee', 'coffee']]
I know about the :include_blank
option, but it's not what I'm looking for because it inserts an empty string into the database, which is not the same as a NULL. 我知道
:include_blank
选项,但这不是我想要的,因为它在数据库中插入了一个空字符串,这与NULL不同。 There are many NULL values already in my database, and I use this form for inserting and editing the Person's records. 我的数据库中已经有许多NULL值,并且我使用此表单来插入和编辑Person的记录。 I need the dropdown list to recognize NULLs so I can edit the other fields in Person without being forced to change the value of hot_drink.
我需要下拉列表来识别NULL,因此我可以在Person中编辑其他字段,而不必强制更改hot_drink的值。
Anyone know how I could go about this? 有人知道我该怎么做吗?
Have you tried 你有没有尝试过
<%= f.select :hot_drink, [['Nothing Selected', nil], ['Tea', 'tea'], ['Coffee', 'coffee']] %>
Try to add a default value to nil
in your migration to handle this case. 尝试在迁移中将默认值添加为
nil
来处理这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.