Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 generated user id after creating the user. But currently it returns true/ false value upon saving

How can I get the saved user id?

like image 740
sameera207 Avatar asked Jun 13 '11 09:06

sameera207


People also ask

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

Can you use ActiveRecord without rails?

ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.

What is ActiveRecord in Ruby on Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

Just call user.id after you've saved.

like image 89
Chowlett Avatar answered Oct 14 '22 08:10

Chowlett