可以通过活动记录中的关联计数来订购吗?

时间:2011-02-10 07:43:57

标签: mysql ruby-on-rails ruby-on-rails-3 activerecord

假设我Posts有许多Comments

是否可以执行ActiveRecord查询以获取大多数评论所订购的帖子?

我很惊讶这个相对常见的查询在普通的旧MySQL中似乎没有一个简单的答案在AR。是的,您可以使用counter_cache,但这并不是真正重新创建原始查询。

我错过了什么?

更进一步。如果Posts有许多Comments有很多Likes,该怎么办?是否有可能获得总数最多的帖子?

谢谢!

3 个答案:

答案 0 :(得分:1)

正如你所说,counter_cache似乎最接近“rails way”。到目前为止,我没有遇到任何针对此特定目的的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语法,但仍然......它有效:)

答案 1 :(得分:0)

如果你愿意,你可以确定你也可以这样做:

posts = Post.find(:all, :include => 'comments')
posts.sort { |a,b| b.comments.count <=> a.comments.count }

答案 2 :(得分:0)

我想你可以使用arel ::

做这样的事情
comments= Comment.arel_table
posts= Post.joins(:comments).order(comments[:id].count)

虽然,我不确定这是否是正确的方法。你必须自己尝试。

相关问题