Skip navigation

Monthly Archives: March 2010

Using Ruby on Rails callbacks, you might be tempted at some point to do this

In your model:
after_save :test_for_something

And then
def test_for_something

if (some_test) then self.errors.add(“Problem”); return true; else return false; end

This is not going to work as it is not handled as a validation. The record will be saved in the db even though this will return false

Similarly, if you are inside a transaction, do not rely on after_save for throwing an exception that would rollback the transaction, as it’s not going to happen.
Doing this inside the after_save will not cause an exception to be thrown
raise ActiveRecord::Rollback

The best way for doing that is keeping validations separate by having a separate validate :method_name method.