Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did I get an ActiveRecord::Relation object?

I tried to get a car instance from database,

theCar = Car.where(:name => 'TOYOTA')
puts theCar.user_name

I got the error message: undefined method `user_name' for ActiveRecord::Relation:0xb6837b54

Why did I get an ActiveRecord::Relation object, and not a Car object?? What could be the cause? By the way, I queried the car inside my migration file. I am using Rails 3.

like image 653
Mellon Avatar asked Apr 01 '11 08:04

Mellon


People also ask

What is an ActiveRecord relation object?

An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is ActiveRecord naming convention?

ActiveRecord expects applications to follow certain naming conventions. These conventions extend from file naming, class naming, table naming and more. By default classes are singular, tables are plural, primary keys are id and foreign keys are table_id.


1 Answers

You get it because you are using Lazy Loading. Nothing is loaded before you will call certain object or objects.

As a matter of fact your query will return an Array of objects: ALL cars with a name TOYOTA. If you know that there is only one CAR with this name you can do this:

theCar = Car.where(:name => 'TOYOTA').first
# or
theCar = Car.first(:name => 'TOYOTA')
# or
theCar = Car.find_by_name('TOYOTA')

And if there is many Cars with name TOYOTA:

theCars = Car.where( :name => "TOYOTA" ).all
theCars.map(&:user_name)
#=> ["Jhon", "Paul" ...]
like image 167
fl00r Avatar answered Nov 01 '22 18:11

fl00r