Rails ActiveRecord在after_save回调中使用最近保存的记录ID [英] Rails ActiveRecord using recently saved record id in after_save callback

查看:360
本文介绍了Rails ActiveRecord在after_save回调中使用最近保存的记录ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在after_save回调中使用最近存储的记录ID,如果是的话,是否可以使用?




after_save:create_children



def create_children

  self.id

end



更新:
对不起,我的保存功能出现了问题,我的错,很遗憾浪费你的时间



感谢

解决方案

我刚刚尝试过:

  class Thing< ActiveRecord :: Base 
after_save:test_me

def test_me
puts self.id
end
end



并在控制台中:

  $ rails c 
加载开发环境(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>

您的模型还有什么变化?


I want to use recently stored record ID in after_save callback, is that possible if yes how?

after_save :create_children

def create_children
 self.id
end

Update: Sorry there was something going wrong with my save function, my bad, sorry to waste your time

Thanks

解决方案

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?

这篇关于Rails ActiveRecord在after_save回调中使用最近保存的记录ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆