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.
after_rollbackis only called on objects that are saved or destroyed during the transaction. Are you setting up theafter_rollbackcallback on your main class or on yourErrorLogclass?In fact, using the
after_rollbackcallback on yourErrorLogclass would seem to be the easiest approach. The only case where you’re going to lose theErrorLoginstances is if the transaction is rolled back so something like this should work: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#savewouldn’t fail as you’re going to be outside the scope of a transaction by that point.