How to get id values after saving an ActiveRecord model in rails

旧巷老猫 提交于 2020-01-01 03:57:09

问题


I have an ActiveRecord model (I'm on rails 2.3.8) called user and I'm saving it as

user = User.new
user.name = "user name"
user.save!

what I want to do is get the generated user id after creating the user. But currently it returns true/ false value upon saving

How can I get the saved user id?


回答1:


Just call user.id after you've saved.




回答2:


For people who looking for on create in model, below is the way:

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



回答3:


the way I did it was

class User < ActiveRecord::Base  
...  
  id = nil
  after_save {id = self.id}
...
end

and then the local variable id is available throughout the model



来源:https://stackoverflow.com/questions/6328693/how-to-get-id-values-after-saving-an-activerecord-model-in-rails

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