Monday, August 5, 2013

before_save vs before_validate in Ruby On Rails

If we want to manipulate data before saving into database we tend to use before_save for example if we want to trim users first name before saving to database we would normally use before_save callback and will do something like below:

before_save :trim_first_name

def trim_first_name
  first_name = first_name.strip
end

But there is gotcha into it, it will skip validation for updated first_name because before_save callback gets executed after validations. So lets say, if there uniqueness validation for first_name and if there is already user with first_name "anil" present in database and if user specify "anil " then that user will be inserted since later one has extra space and it skips that validation and before saving into database it strips the first_name and defeats the purpose of our validation.

Hence, whenever we want to manipulate data before saving into database its good idea to have before_validation callback instead of before_save callback.

Same can be achieved like below:

before_validation :trim_first_name

def trim_first_name
  first_name = first_name.strip
end

No comments:

Post a Comment