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

Viewed 41873

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?

3 Answers

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
Related