I registered an after_commit trigger for one of my Active Record entities, like so:
class Work < ActiveRecord::Base
after_commit :on_work_commit
...
def on_work_commit
puts self.id # prints nil sometimes
end
end
The problem is that in my production environment, self.id is sometimes nil inside the on_work_commit method. It doesn't happen all the time, in fact, it happens intermittently. By analysing the stack trace of these errors, I can see that they happen intermittently during the work creation operation, but never when updating a work. I am unable to reproduce this problem locally though, as it only happens in production when a lot of works are being created and updated at the same time.
This kind of problem screams race condition to me, but I have no idea what could be wrong. Is there any scenario where an after_commit trigger could be called for an object before the object could get an id?
I'm using rails version 3.2.22 and ruby version 1.9.3-p484.
after_commit
method also executes for destroy
action, that's why its returning nil
when you are trying to delete an item, do this instead
after_commit :on_work_commit, on: [:create, :update]
I would suggest you to use after_save
for this purpose
after_save :on_work_commit
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With