Rails 3,Active Record查询返回ActiveRecord :: Relation对象,而不是对象

JP *_*shy 28 activerecord ruby-on-rails ruby-on-rails-3

由于我对新的ActiveRecord查询接口的误解,我觉得这是一个简单的问题,但是举个例子:

>> Category.first.recipes
=> [ ... ] # array of recipes
Run Code Online (Sandbox Code Playgroud)

然而:

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

这里发生了什么?为什么我的where方法返回一个ActiveRecord::Relation对象?如何从查询中检索对象?

Swa*_*and 43

这实际上是故意的.

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}})
Run Code Online (Sandbox Code Playgroud)

只有在调用first,each等特殊方法时才会检索对象.这称为延迟加载,当您想要缓存视图时,这是一个很好的.阅读更多有关原因的 信息.

  • 投票,因为它不相同.`where`返回ActiveRecord :: Relation,其余返回Array或Model.class (4认同)
  • 它在上下文中是等价的.这就是我提到延迟加载的原因.但是,`.where.all`将是等效的. (2认同)

Aus*_*Lin 6

Category.where(:id => 1).recipes
Run Code Online (Sandbox Code Playgroud)

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