I have several before_validation callbacks that operate on the attributes being set on my model. I run into trouble when I have a situation like this:
class Foo < ActiveRecord::Base
before_validation :capitalize_title
validates :title, :presence => true
def capitalize_title
title.upcase
end
end
I write a test to ensure that ‘nil’ title is not allowed, but the test gets an error because the nil.upcase is not defined. I’d like to handle this error, but I already have error handling that runs after before_validation callbacks.
I don’t want to put checks around all of my before_validation callbacks to make sure the data exists, if I can avoid it.
Is there a clean or accepted way to deal with this type of situation?
Just check if you have a title. And don’t forget to save the modified title.
If you need to patch things up with a
before_validationhook then you’re stuck with taking care of invalid data in two places. If your validation was complicated you could factor it into two pieces: one piece that has to be true before thebefore_validationcan run and one piece that has to be true after thebefore_validationhas run: