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?
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.
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? 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.
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.
Category.where(:id => 1).recipes
Returns an array. If you simply do Category.where(:id => 1).first.recipes
it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With