I'm trying to write a query for a personal site I'm building where users can post and rate others' opinions. With regards to rating opinions, I have it so users can rate opinions either up or down and then I would like to display two separate pages for the opinions rated up and rated down order by the highest count.
I have a many-to-many relationship between Opinions
and Ratings
. They are joined together by a table called OpinionRatings
.
I've written a query for the page with opinions that have been rated up which is the following:
@topUpRatings = Rating.find(
:all,
:select => "opinion_ratings.opinion_id, opinion_ratings.account_id",
:joins => "inner join opinion_ratings on ratings.id=opinion_ratings.rat开发者_运维知识库ing_id",
:conditions => ["ratings.up=?", true]
)
This returns each opinion id and account id which I was going to use to perform additional query to display the opinion and the user who post it.
The problem I am having is that I can not figure out a way to sort the opinions by the count of ups (if that makes sense).
I know there is count(*)
and group by, but I just can not seem to figure out how to integrate that into an order by statement.
I've been thinking of sub queries, but those are only allowed in select, from, and where.
Any help would be appreciated. If you need more information please ask.
@topUpRatings = Rating.find(
:all,
:select => "opinion_ratings.opinion_id, count(opinion_ratings.account_id)",
:joins => "inner join opinion_ratings on ratings.id=opinion_ratings.rating_id",
:conditions => ["ratings.up=?", true]
:group_by => "opinion_ratings.opinion_id"
:order_by => "count(opinion_ratings.account_id) DESC"
)
I am not sure about the syntax, but tried to get the idea across.
精彩评论