Ruby-on-rails 在 Rails 中保存 ActiveRecord 模型后如何获取 id 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6328693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:23:18  来源:igfitidea点击:

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

ruby-on-railsactiverecord

提问by sameera207

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

我有一个名为 user 的 ActiveRecord 模型(我在 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. But currently it returns true/ false value upon saving

我想要做的是在创建用户后获取生成的用户 ID。但目前它在保存时返回真/假值

How can I get the saved user id?

如何获取已保存的用户 ID?

回答by Chowlett

Just call user.idafter you've saved.

user.id保存后调用即可。

回答by Ravistm

For people who looking for on createin 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

回答by jsamm

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 在整个模型中可用