避免加载关联关系的对象 [英] Avoid loading associated relationship objects

查看:134
本文介绍了避免加载关联关系的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我on Rails的3.0.7使用Ruby和,出于性能的原因,我想避免检索类obect加载关联的对象。也就是说,如果我有一个的has_many一个文章类\\型号:用户语句,我想不会加载相关用户对象时,我检索文章对象(我觉得这个行为依赖于Ruby on Rails的约定优于配置原则)。

I am using Ruby on Rails 3.0.7 and, for performance reason, I would like to avoid loading associated objects on retrieving a class obect. That is, if I have an Article class\model with a has_many :users statement I would like to not load associated User objects when I retrieve an Article object (I think this behavior depends on the Ruby on Rails "Convention over Configuration" principle).

我怎么能这样做?

推荐答案

正如又一怪胎,滑轨(ActiveRecord的)指出默认不加载的关系的对象。相反,它会和让他们当你问他们。如果你不需要这种关系的对象,它永远不会刻意去加载它们,节省了数据库时。

As noted by Yet Another Geek, Rails (ActiveRecord) doesn't load the relationship objects by default. Rather, it goes and gets them when you ask for them. If you don't need the objects of that relationship, it will never bother to load them, saving database time.

如果你确实需要的话,它会去检索它们懒洋洋地(默认情况下)。如果你知道你需要的关系对象的所有(或多个)(假定的x一对多),那么你可以使用:包括修改你的找到把他们都弄到前面(这将是快了很多,因为它可以做到这一点与一个单一的数据库调用)。了解和采取的热切负荷关系对象的能力优势是一个重要的事情。

If you do need then, it will go retrieve them lazily (by default). If you know you'll need all (or many) of the objects of the relationship (assuming x-to-many), then you can use the :include modifier to your find to get them all up front (which will be a lot faster since it can do that with a single db call). Knowing and taking advantage of the ability to eagerly load relationship objects is an important thing.

@person = Person.find(params[:id], :include => :friends)

所有这一切是说,你想要的行为(不加载的对象,如果你不需要他们)是默认的行为,你应该准备就绪。答案的其余部分只是一些方面,可能对你有用更高版本。

All that being said, the behavior you want (not loading the objects if you don't need them) is the default behavior and you should be all set. The rest of the answer was just some context that may be useful to you later.

这篇关于避免加载关联关系的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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