与 Arel 的预加载关联计数 (Rails 3)
-
25-09-2019 - |
题
简单任务:鉴于一篇文章有很多评论,能够在一长串文章中显示每篇文章有多少评论。我正在尝试弄清楚如何使用 Arel 预加载这些数据。
的“复杂聚合”部分 自述文件 文件似乎讨论了这种类型的情况,但它并没有完全提供示例代码,也没有提供一种在两个查询而不是一个连接查询中执行此操作的方法,这对性能来说更差。
鉴于以下情况:
class Article
has_many :comments
end
class Comment
belongs_to :article
end
如何预加载一篇文章并设置每篇文章有多少条评论?
解决方案
你可以使用 SQL 做一些令人讨厌的事情,例如:
default_scope :select => 'articles.*, (select count(comments.id) from comments where comments.article_id = articles.id) as count_comments'
然后您就可以访问 Article.first.count_comments。
另一种(更好的)方法是使用“counter_cache”功能/选项 属于 协会。
其他提示
你不能使用计数器缓存呢?
belongs_to :article, :counter_cache => true
您还需要有一个迁移,增加了列comments_count
不隶属于 StackOverflow