Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Active Record has nil id after commit

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.

like image 603
Tavio Avatar asked Aug 31 '25 16:08

Tavio


1 Answers

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!

like image 57
Rajdeep Singh Avatar answered Sep 03 '25 01:09

Rajdeep Singh