简体   繁体   English

Ruby on Rails和渴望加载模型关联(包括或不包括)?

[英]Ruby on Rails and eager loading model associations (to include or not to include)?

So perhaps this is a dumb question, but I've been reading the the rails guide on the model associations and am trying to figure out if I need to use an include or not. 所以也许这是一个愚蠢的问题,但我一直在阅读关于模型关联的rails指南,并试图弄清楚我是否需​​要使用include。

So if I have a model for article and an article has_many comments, the comments are eager loaded. 因此,如果我有一篇文章模型和一篇文章has_many评论,那么评论就会被加载。 However, if I'm frequently accessing the author of the comment from the article model I would need to use an :include to eager load it. 但是,如果我经常从文章模型访问评论的作者,我需要使用:include来急切加载它。 This makes sense to me. 这对我来说很有意义。

However, what happens if I call a model method like @article.comments.author_named_sam? 但是,如果我调用像@article.comments.author_named_sam?这样的模型方法会发生什么@article.comments.author_named_sam? which uses the author. 它使用作者。

Would placing an include in the article model to ensure author is eager loaded mean that when this method is called and in turn queries the author, that this is using the eager loaded author? 在文章模型中放置一个包含以确保作者是热切的加载意味着当调用此方法并反过来查询作者时,这是使用热切的加载作者?

if the include is specified for author then the author object will be used from loaded objects only when it called from comment object using association(standard rails way). 如果为author指定了include,则只有在使用关联(标准rails方式)从comment对象调用时,才会从加载的对象中使用author对象。

like following; 喜欢以下;

def author_named_sam?
  author.name == 'sam' 
end

You can try by following code and analyze the queries made to database from console 您可以尝试按照代码并分析从控制台对数据库进行的查询

Article.includes(comments: [:author]).find(1) 

In my opinion, using eager loading in associations often is not a good idea, because it easily can become problematic for performance. 在我看来,在关联中使用急切加载通常不是一个好主意,因为它很容易成为性能问题。

It's better practice, in my opinion, explicitly eager-load association only when you need them. 在我看来,这是一种更好的做法,只有在你需要它时才能明确地加载关联。 I mean using :includes during querying. 我的意思是使用:includes在查询期间。

For instance, query like this: 例如,查询如下:

Article.includes(comments: :author)

will load comments and author objects along with articles. 将加载评论和作者对象以及文章。 Thus avoiding N+1 queries and not forcing you to make artificial decisions in designing your models. 因此,避免N+1查询,而不是强迫您在设计模型时做出人为决定。

http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

There are some caveats with includes method though. 还有一些注意事项与includes法虽然。 See this excellent post on more details about includes and other related methods. 有关includes和其他相关方法的更多详细信息,请参阅此优秀文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM