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 = User.new
user.name = "user name"
user.save!
what I want to do is get the gener开发者_运维百科ated user id after creating the user. But currently it returns true/ false value upon saving
How can I get the saved user id?
Just call user.id
after you've saved.
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
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
精彩评论