Can I order by counting associations in the active record?

Suppose I have Postswith manyComments

Can I run an ActiveRecord query to get posts sorted by most comments?

I am surprised that this relatively common query in plain old MySQL does not seem to have an easy answer in AR. Yes, you can use counter_cache, but this does not recreate the original request.

What am I missing?

Let's take one more step. What to do if it Postshas a lot Commentsthat have a lot Likes. Is it possible to receive messages with the most comments in the aggregate?

Thank!

+3
source share
3 answers

, 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 , ... :)

+1

, - , :

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

, - isl::

comments= Comment.arel_table
posts= Post.joins(:comments).order(comments[:id].count)

, , . .

0

Source: https://habr.com/ru/post/1791151/


All Articles