与 Arel 的预加载关联计数 (Rails 3)

发布于 2024-08-28 01:30:22 字数 421 浏览 8 评论 0原文

简单的任务:假设一篇文章有​​很多评论,能够在一长串文章中显示每篇文章有多少评论。我正在尝试弄清楚如何使用 Arel 预加载这些数据。

README 文件的“复杂聚合”部分似乎讨论了这一点类型的情况,但它并没有完全提供示例代码,也没有提供一种在两个查询而不是一个连接查询中执行此操作的方法,这对性能来说更差。

鉴于以下情况:

class Article
  has_many :comments
end

class Comment
  belongs_to :article
end

如何预加载一篇文章并设置每篇文章有多少条评论?

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.

Given the following:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橘香 2024-09-04 01:30:22

你不能为此使用计数器缓存吗?

belongs_to :article, :counter_cache => true

您还需要进行添加列 comments_count 的迁移

Can't you use counter cache for this?

belongs_to :article, :counter_cache => true

You also need to have a migration that adds the column comments_count

疯狂的代价 2024-09-04 01:30:22

你可以使用 SQL 做一些令人讨厌的事情,比如:

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

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

另一种(更好的)方法是使用 属于协会。

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'

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文