Neil
Neil

Reputation: 5188

Rails collection_select: save null instead of empty string when 'blank' option selected

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.

Upvotes: 4

Views: 2484

Answers (2)

Teoulas
Teoulas

Reputation: 2963

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

Upvotes: 2

Neil
Neil

Reputation: 5188

This works:

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

Upvotes: 2

Related Questions