与 Arel 的预加载关联计数 (Rails 3)
简单的任务:假设一篇文章有很多评论,能够在一长串文章中显示每篇文章有多少评论。我正在尝试弄清楚如何使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能为此使用计数器缓存吗?
您还需要进行添加列 comments_count 的迁移
Can't you use counter cache for this?
You also need to have a migration that adds the column comments_count
你可以使用 SQL 做一些令人讨厌的事情,比如:
然后你就可以访问 Article.first.count_comments。
另一种(更好的)方法是使用 属于协会。
You can do something nasty using SQL like:
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.