渴望加载关联计数与Arel(Rails 3) [英] Eager-loading association count with Arel (Rails 3)

查看:77
本文介绍了渴望加载关联计数与Arel(Rails 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的任务:假设一篇文章有​​很多评论,则可以在长长的文章列表中显示每篇文章有多少评论。我正在尝试找出如何使用Arel预加载此数据。

Simple task: given that an article has many comments, be able to display in a long list of articles how many comments each article has. I'm trying to work out how to preload this data with Arel.

自述文件文件似乎在讨论这种情况,但它并未提供示例代码,也未提供方法在两个查询中而不是一个联合查询中执行,这会降低性能。

The "Complex Aggregations" section of the README file seems to discuss that type of situation, but it doesn't exactly offer sample code, nor does it offer a way to do it in two queries instead of one joined query, which is worse for performance.

给出以下内容:

class Article
  has_many :comments
end

class Comment
  belongs_to :article
end

如何为文章预载设置每个评论有多少?

How can I preload for an article set how many comments each has?

推荐答案

您可以使用SQL进行讨厌的操作,例如:

You can do something nasty using SQL like:

default_scope :select => 'articles.*, (select count(comments.id) from comments where comments.article_id = articles.id) as count_comments'

,然后您就可以访问Article.first.count_comments。

and then you would have access to Article.first.count_comments.

另一种(更精细的)方法是使用 counter_cache功能/ a from 属于关联。

Another (nicer) method to do it is to use the 'counter_cache' feature/option from belongs_to association.

这篇关于渴望加载关联计数与Arel(Rails 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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