I have a model Issue. Issues have Comments and Votes through join models. In my issues#index view, I would like to be able to sort the query results by the number of comments and votes as so:
@issues = Issue.limit(10).find(:all, :order => "COMMENT_COUNT DESC")
However if I try something like:
@issues = Issue.limit(10).find(:all, :order => "issue.comments.count DESC")
it doesn’t work. I can probably add a comment and vote count to the issue model…but i’m not sure what the best way to do that is and I don’t even think it is the best way.
How should I be doing that?
It’s a little bit more involved than this. This requires a bit more sql. You have to include the comments table in the query for your issues. You then have to group the results by the Issue id to get the count of comments per issue.
Something like this should work: