1

In my model I have custom validation method that sends request to the external service. Based on the response I add errors to errors array if any.

If there are errors, I also need to create new records of ErrorLog models, which represents error log. The problem is that when validation fails, it performs ROLLBACK on database, and all my new ErrorLog records are lost. What is the best way to implement it?

I also should say that after_rollback is not called for some reason.

1 Answer 1

3

after_rollback is only called on objects that are saved or destroyed during the transaction. Are you setting up the after_rollback callback on your main class or on your ErrorLog class?

In fact, using the after_rollback callback on your ErrorLog class would seem to be the easiest approach. The only case where you're going to lose the ErrorLog instances is if the transaction is rolled back so something like this should work:

class MyClass < ActiveRecord::Base
  before_save :check_external

  def check_external
    unless external_says_i_am_okay?
      ErrorLog.create!(:message => 'oops')
    end
  end
end

class ErrorLog < ActiveRecord::Base
  after_rollback :save_anyway

  def save_anyway
    self.save!
  end
end

Of course having said all that you might want to consider the performance of getting an external service to validate your models. It might not be sufficiently quick if you're creating objects in the scope of a web request for example. You'd also want to make sure that the ErrorLog#save wouldn't fail as you're going to be outside the scope of a transaction by that point.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for helping. I understand my mistake and set up after_rollback inside ErrorLog model. But self.save! don't do anything. I have SQL (0.1ms) BEGIN \n SQL (0.1ms) COMMIT in the log, without any insertations.
I wonder if it thinks it is already saved because it was 'saved' in the transaction itself. You might want to try calling touch on it or changing an attribute to see if that nudges the save into life. Worth checking too that the callback is definitely being called by logged in there.
Only with ErrorLog.create!(self.attributes) I can acheive that error has been saved. It looks like dirty hack, but I don't know, what else to do. Thanks for help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.