# Nulls changing to blanks

**URL:** <https://www.ruby-forum.com/t/nulls-changing-to-blanks/53808>\
**Category:** Rails\
**Created:** [February 14, 2006, 7:29pm UTC](https://www.ruby-forum.com/t/nulls-changing-to-blanks/53808 "2006-02-14T19:29:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![dandante](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/9fc29f/32.png) [@dandante](https://www.ruby-forum.com/u/dandante)\
**Post date:** [February 14, 2006, 7:29pm UTC](https://www.ruby-forum.com/t/nulls-changing-to-blanks/53808/1 "2006-02-14T19:29:19Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![dandante](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/9fc29f/32.png) [@dandante](https://www.ruby-forum.com/u/dandante)\
**Post date:** [February 15, 2006, 11:58am UTC](https://www.ruby-forum.com/t/nulls-changing-to-blanks/53808/2 "2006-02-15T11:58:50Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![dandante](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/9fc29f/32.png) [@dandante](https://www.ruby-forum.com/u/dandante)\
**Post date:** [February 15, 2006, 10:08pm UTC](https://www.ruby-forum.com/t/nulls-changing-to-blanks/53808/3 "2006-02-15T22:08:29Z")

</div>

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.
