简体   繁体   English

Ruby on Rails查询

[英]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 . 我的OpinionsRatings之间存在多对多关系。 They are joined together by a table called OpinionRatings . 它们通过称为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. 这将返回我将用于执行其他查询以显示意见和发布意见的用户的每个意见ID和帐户ID。

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. 我知道有count(*)和group by,但是我似乎无法弄清楚如何将其集成到by by语句中。

I've been thinking of sub queries, but those are only allowed in select, from, and where. 我一直在考虑子查询,但是这些子查询只允许在select,from和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. 我不确定语法,但试图将其理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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