user1943735
user1943735

Reputation: 155

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. 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. There are many NULL values already in my database, and I use this form for inserting and editing the Person's records. 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.

Anyone know how I could go about this?

Upvotes: 1

Views: 735

Answers (1)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

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.

Upvotes: 1

Related Questions