Nulls changing to blanks


#1

Hi,

I have forms that are used to update rows in a table. There are some
columns that allow nulls in the table.

Say that column X is allowed to be null. The text box for column X shows
up with nothing in it because it is null. When I hit submit on the
update page, the value of that column is changed from null to blank (the
empty string, or ‘’). This might sound trivial, but there is a different
code base that expected nulls and had to be fixed to work around this.

Of course, I can stop this from happening in my controller by doing
something like this:
form = params[:item]
if form[:x] == ‘’
form.delete(“x”)
end

But that’s not the approach I want to use. I want to disable this
behavior globally. Basically, for any column that allows nulls, I don’t
want it mentioned in insert and update queries if its value in the form
is the empty string.

Is there a switch or something to turn on this behavior?
Thanks


#2

This came up not too long ago, I think the solution was to add a
before_save to all your models to change blank strings to nil:

class ActiveRecord::Base
def before_save
attributes.each do |key, value|
self[key] = nil if value.blank?
end
end
end

I haven’t tested it, but something like that should work.

Cheers, Jonathan.


#3

Jonathan V. wrote:

class ActiveRecord::Base
def before_save
attributes.each do |key, value|
self[key] = nil if value.blank?
end
end
end

That appears to work. Thanks.