Rails 3: cancel insert on after_save

972 views Asked by At

I have a model that, when a record is inserted, needs to call a webservice.

If the webservice fails ( timeout or other failures ), them the save in database should also be reverted.

I used the after_save callback and tried to raise an ActiveRecord::Rollback when this kind of error happens.

Although it returns false on object.save, it doesn't rollback the transaction. What is the proper way of doing this?

How can i also make sure that the record won't be created?

2

There are 2 answers

0
Anil On

Are you wrapping this in an Active Record Transaction block?

User.transaction do
  User.create(:username => 'Kotori')
  User.transaction(:requires_new => true) do
    User.create(:username => 'Nemu')
    raise ActiveRecord::Rollback
  end
end

Also See:

http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

1
Pavel Strakhov On

Try to use before_save and return false from it.