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.
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
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.
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.