4

I have the following code for a select box in a form:

<div class="field">
  <%= f.label :user_id %>
  <%= f.collection_select :user_id, User.all, :id, :name, include_blank: true %>
</div>

And it displays the following select options:

select options

I noticed that when the blank option is selected, what actually gets saved in the database is an empty string: ''

I do not want to save an empty string when the blank option is selected. Instead: I want to save null.

I attempted overriding the setter in the rails model but it didn't work:

def text_value=(value)
  write_attribute(:name, nil) and return if value.empty?
  super
end

How might I do this at the application level? I am aware that I could have a Default Value specified at the Database level, but it seems that this might be better suited at the application level.

2
  • Isn't that just a wrong representation that you are looking at? I mean, an integer field will never be an empty string. It can be either a number or null, right? Commented Nov 2, 2016 at 18:50
  • In this circumstance: no. If the blank option is selected then that would mean that the user has not selected an answer, thus null. Pretend that there is another select option that specifies 'does not apply' or 'no' and which actually saves a blank string value. Saving it as null in the database is just a way for me to say 'oh ok, they did not answer this question at all. Commented Nov 2, 2016 at 18:53

2 Answers 2

2

This works:

def text_value=(value)
  if value.empty?
    write_attribute(:name, nil)
  else
    super
  end
end
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to do this for multiple attributes and/or models, there's a gem for that: https://github.com/rubiety/nilify_blanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.