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等特殊方法时才会检索对象.这称为延迟加载,当您想要缓存视图时,这是一个很好的.阅读更多有关原因的 信息.
Category.where(:id => 1).recipes
Run Code Online (Sandbox Code Playgroud)
返回一个数组.如果你只是这样做Category.where(:id => 1).first.recipes
应该工作.