Question

I have an array of posts. I want to order this array of posts by number of comments they have (First object in the array being most comments, last being the least). A Post has many comments. This seems like a simple problem, but I can't figure out how to order them. I've tried and I don't believe it's possible to achieve this via the order method. Is there a Rails method I don't know about? Or will I have to home roll it? Thanks in advance!

PS: My relation of comments to posts is polymorphic Comment - (belongs_to :threadable)

Was it helpful?

Solution

You can do this with a complicated active record query, however, the easiest thing by far is to just add a :counter_cache on association. You just add a field on your Post model called comments_count and then in your Comment model:

belongs_to :post, counter_cache: true

Then since it's just a column like all your other columns you can order by it.

See: http://guides.rubyonrails.org/association_basics.html

OTHER TIPS

The easiest way to do this would probably be using the counter_cache option

see:

-

class Comment
  belongs_to :post, counter_cache: true
end

add the column comments_count to the posts database table, then order by that

The best way to achieve it is to use counter cache feature. You need to add integer column to your posts table called comments_count. Then on your comments model you need to change your post association to read:

 belongs_to :post, counter_cache: true

Rails will handle comments_count column to show how many comments are associated with given post. You can then use this column for ordering.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top