简体   繁体   English

在rails中保存ActiveRecord model后如何获取id值

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

I have an ActiveRecord model (I'm on rails 2.3.8) called user and I'm saving it as我有一个名为 user 的 ActiveRecord model (我在 Rails 2.3.8 上),我将其保存为

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

what I want to do is get the generated user id after creating the user.我想要做的是在创建用户后获取生成的用户 ID。 But currently it returns true/ false value upon saving但目前它在保存时返回真/假值

How can I get the saved user id?如何获取保存的用户 ID?

Just call user.id after you've saved.保存后只需调用user.id

For people who looking for on create in model, below is the way:对于在 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

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然后局部变量 id 在整个 model 中可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM