简体   繁体   English

如何使用Ruby on Rails在下拉列表中允许NULL值?

[英]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.

相关问题 我如何在Rails 2.0上的Ruby上使用jQuery创建选定的下拉列表? - How i can make a selected drop down list using jQuery on ruby on rails 2.0 ? 如何将元素添加到 Rails 的下拉列表中? - How can i add elements into drop down list in rails? 如何在Rails 2.0中创建下拉列表? - how can I make a drop down list in Rails 2.0? 使用Ruby on Rails创建分层的,选择分组的下拉列表 - Creating a hierarchical, optgrouped, drop down list using Ruby on Rails 如何使用带硒的页面对象宝石(红宝石和黄瓜)单击div(下拉) - How I can click on div(drop-down) using page-object gem with selenium (ruby-on-rails and cucumber) ruby on rails如何使用FormOptionHelpers创建动态下拉列表 - ruby on rails how to use FormOptionHelpers to create dynamic drop down list Ruby Rails-NoMethodError,下拉列表 - Ruby Rails - NoMethodError , drop-down list Ruby on Rails-从模型下拉列表 - ruby on rails - drop down list from model 如何在Ruby on Rails中修复不显示任何项目的Navbar下拉菜单 - How can I fix a Navbar drop-down menu in Ruby on Rails that does not show any of the items 如何在Rails中向collection_select(下拉列表)添加/删除值? - How do I add/remove values to a collection_select (Drop-Down List) in Rails?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM