Flexoid
Flexoid

Reputation: 4245

Need to write to db from validation

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.

Upvotes: 1

Views: 393

Answers (1)

Shadwell
Shadwell

Reputation: 34774

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.

Upvotes: 3

Related Questions