简体   繁体   中英

Ruby on Rails Query

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.rating_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM