Forum: Ruby on Rails nulls changing to blanks

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dan T. (Guest)
on 2006-02-14 20:29
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
Jonathan V. (Guest)
on 2006-02-15 12:58
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.
Dan T. (Guest)
on 2006-02-15 23:08
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.
This topic is locked and can not be replied to.