Rails Active Record在提交后具有nil id

Tav*_*vio 2 ruby ruby-on-rails rails-activerecord

我为我的一个Active Record实体注册了一个after_commit触发器,如下所示:

class Work < ActiveRecord::Base
    after_commit :on_work_commit

    ...

    def on_work_commit
        puts self.id # prints nil sometimes
    end
end
Run Code Online (Sandbox Code Playgroud)

问题是在我的生产环境中,self.id有时在on_work_commit方法中是零.它不会一直发生,实际上它是间歇性发生的.通过分析这些错误的堆栈跟踪,我可以看到它们在工作创建操作期间间歇性地发生,但从未在更新工作时发生.我无法在本地重现此问题,因为它只会在生产中同时创建和更新许多作品时发生.

这种问题让我感到愤怒,但我不知道会出现什么问题.是否有任何情况可以在对象获取id之前为对象调用after_commit触发器?

我使用rails版本3.2.22和ruby版本1.9.3-p484.

Raj*_*ngh 5

after_commit方法也执行destroy动作,这就是为什么它nil在你试图删除一个项目时返回,改为执行此操作

after_commit :on_work_commit, on: [:create, :update]
Run Code Online (Sandbox Code Playgroud)

我建议你after_save为此目的使用

after_save :on_work_commit
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!