Skip navigation

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: