2010-12-13 109 views
25

我觉得这是一个简单的问题,由于我对新的ActiveRecord查询接口的误解,但以此为例:Rails 3,Active Record查询返回ActiveRecord :: Relation对象,而不是对象

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

但是:

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

这是怎么回事吗?为什么我的where方法返回一个ActiveRecord::Relation对象?我该如何从查询中检索对象?

回答

42

这其实是故意的。

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}}) 

只有在调用像first,each等特殊方法时才会检索对象。这被称为延迟加载,当你想缓存你的视图时,这是一个很好的选择。详细了解为什么here

+4

投下来,因为它不等效。 'where'返回ActiveRecord :: Relation,其余返回Array或Model.class – 2010-12-26 12:20:02

+2

它在上下文中是等价的。这就是为什么我提到懒加载。但是,“.where.all”是等同的。 – Swanand 2010-12-27 05:02:55

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

返回一个数组。如果你只是做Category.where(:id => 1).first.recipes它应该工作。

3

但是,如果你只是在做一个违反id的地方,使用find方法 Category.find(1)将返回一个Category对象。
因此:
Category.find(1).recipes

相关问题