Rails ActiveRecord using recently saved record id in after_save callback [closed]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 10:29:16

I just tried it with this:

 class Thing < ActiveRecord::Base
   after_save :test_me

   def test_me
     puts self.id
   end
 end

and in the console:

$ rails c
Loading development environment (Rails 3.0.4)
>> x=Thing.new
=> #<Thing id: nil, name: nil, created_at: nil, updated_at: nil>
>> x.save
2
=> true
>> y=Thing.create
3
=> #<Thing id: 3, name: nil, created_at: "2011-04-27 15:57:03", updated_at: "2011-04-27 15:57:03">

What else is going on in your model?

if you call reload() after saving the object, the self.id will be populated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!