Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3, Active Record query returns ActiveRecord::Relation object, instead of objects

I feel like this is a simple problem I'm having due to my misunderstanding of the new ActiveRecord query interface, but take this example:

>> Category.first.recipes => [ ... ] # array of recipes 

However:

>> Category.where(:id => 1).recipes => NoMethodError: undefined method `recipes' for #<ActiveRecord::Relation:0x000001033dc9e0> 

What's going on here? why does my where method return an ActiveRecord::Relation object? how can I retrieve the objects from the query here?

like image 419
JP Silvashy Avatar asked Dec 13 '10 06:12

JP Silvashy


People also ask

What is an ActiveRecord relation object?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

What is ActiveRecord :: Base in Rails?

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... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…

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.


2 Answers

This is actually intentional.

Category.where(:id => 1) # Is Equivalent to Category.all(:conditions => {:id => 1}}) Category.where(:id => 1).first # Is equivalent of Category.first(:conditions => {:id => 1}}) 

The objects are only retrieved when special methods like first, each etc are called. This is called lazy loading which is a great when you want to cache your views. Read more about why here.

like image 152
Swanand Avatar answered Sep 21 '22 18:09

Swanand


Category.where(:id => 1).recipes 

Returns an array. If you simply do Category.where(:id => 1).first.recipes it should work.

like image 33
Austin Lin Avatar answered Sep 17 '22 18:09

Austin Lin