[英]How to get id values after saving an ActiveRecord model in rails
我有一個名為 user 的 ActiveRecord model (我在 Rails 2.3.8 上),我將其保存為
user = User.new
user.name = "user name"
user.save!
我想要做的是在創建用戶后獲取生成的用戶 ID。 但目前它在保存時返回真/假值
如何獲取保存的用戶 ID?
保存后只需調用user.id
。
對於在 model 中尋找創建的人,方法如下:
class User < ActiveRecord::Base
...
after_create :do_something
def self.do_something
user_id = id #this will have last created id
# use this according to your needs
end
...
end
我這樣做的方式是
class User < ActiveRecord::Base
...
id = nil
after_save {id = self.id}
...
end
然后局部變量 id 在整個 model 中可用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.