set empty values as null in the database

Le’s say that I have a table called people and the column middle_name is nullable. If the user enters say blank or empty space then in the database it is recorded as empty space. I would like in all my models all empty spaces to be recorded as null.

I guess I can write a plugin which will do so for all the models but I’m sure something like that should already be existing.I checked but couldn’t find anything. Anyone knows any plugin which might be of help.

Thanks

I think you should be able to use a before_save hook in you person model to change empty strings to nil... or do it application wide with an extention to AR.

class ActiveRecord::Base

  def before_save     attributes.each { |key, value| write_attribute(key, nil) if value.is_a?(String) && value.blank? }   end

end

Hope this helps.

Neeraj Kumar wrote:

Le's say that I have a table called people and the column middle_name is nullable. If the user enters say blank or empty space then in the database it is recorded as empty space. I would like in all my models all empty spaces to be recorded as null.

WhitespaceKiller does this

http://wiki.rubyonrails.org/rails/pages/HowToStripWhitespaceFromModelFields

I’m still learning ruby and my question is:

If a model is using before_save method in the fashion you have illustrated then this before_save method would be overriden by the before_save method of the model and empty string will be persisted.

Neeraj,

That is true - but the model can also simply call super() from the before_save() to keep this functionality.

There are also a bunch of callbacks you can choose from: http://caboo.se/doc/classes/ActiveRecord/Callbacks.html