[英]Possible to order by the count of an association in active record?
让我们说我的Posts
有很多Comments
是否可以执行ActiveRecord查询以获取大多数评论所订购的帖子?
我很惊讶这个相对常见的查询在普通的旧MySQL中似乎没有一个简单的答案在AR。 是的,您可以使用counter_cache,但这并不是真正重新创建原始查询。
我错过了什么?
更进一步。 如果Posts
有很多Comments
有很多Likes
怎么办? 是否有可能获得总数最多的帖子?
谢谢!
正如你所说,counter_cache似乎最接近“轨道方式”。 到目前为止,我没有遇到任何针对此特定目的的AR定义方法,但这是我所看到的最接近它的方法:
@posts = Post.select("posts.*, COUNT(comments.id) AS count_comments").joins("LEFT OUTER JOIN comments ON posts.id = comments.post_id").group("posts.id").order("count_comments DESC")
@posts.each do |post|
puts "Comments: #{post.count_comments}"
end
自定义选择以包含count_comments属性。 加入而不是include,因为include将覆盖select语法。 自定义连接语法而不仅仅是:注释,否则它将是一个内连接,它将阻止检索没有注释的帖子。
这基本上是自己编写整个SQL语法,但仍然......它的工作原理:)
如果你想要,你可以确定你也可以这样做:
posts = Post.find(:all, :include => 'comments')
posts.sort { |a,b| b.comments.count <=> a.comments.count }
我想你可以用arel做这样的事情::
comments= Comment.arel_table
posts= Post.joins(:comments).order(comments[:id].count)
虽然,我不确定这是否是正确的方法。 你必须自己尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.