轨道3,活动记录查询返回的ActiveRecord ::关系的对象,而不是对象 [英] Rails 3, Active Record query returns ActiveRecord::Relation object, instead of objects

查看:94
本文介绍了轨道3,活动记录查询返回的ActiveRecord ::关系的对象,而不是对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

不过:<​​/ P>

However:

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

这是怎么回事呢?为什么我的其中,方法返回一个的ActiveRecord ::关联对象?我怎么可以在这里查询检索对象?

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?

推荐答案

这其实是故意的。

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

该对象时的特殊方法,如第一个,每个等被称为只检索。这就是所谓的延迟加载,当你希望缓存你的意见这是一个伟大的。了解更多关于为什么这里

这篇关于轨道3,活动记录查询返回的ActiveRecord ::关系的对象,而不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆