Ruby-on-rails Rails 3、Active Record 查询返回 ActiveRecord::Relation 对象,而不是对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4426441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:52:32  来源:igfitidea点击:

Rails 3, Active Record query returns ActiveRecord::Relation object, instead of objects

ruby-on-railsactiverecordruby-on-rails-3

提问by JP Silvashy

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:

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

>> 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 wheremethod return an ActiveRecord::Relationobject? how can I retrieve the objects from the query here?

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

回答by Swanand

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.

仅在调用诸如 first、each 等特殊方法时才检索对象。这称为延迟加载,这在您想要缓存视图时非常有用。在此处阅读更多有关原因的 信息

回答by Austin Lin

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

Returns an array. If you simply do Category.where(:id => 1).first.recipesit should work.

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

回答by cpuguy83

But if you are just doing a where against the id, use the find method Category.find(1)will return a Category object.
So:
Category.find(1).recipes

但是如果你只是针对 id 做一个 where,使用 find 方法 Category.find(1)会返回一个 Category 对象。
所以:
Category.find(1).recipes