按项目关联表排序

时间:2015-05-26 16:29:56

标签: ruby-on-rails postgresql

我有模型Gif,其中包含has_many gif_statisticsGifStatistic模型的字段status包含可能的选项:likedislike。 我有查询喜欢 Gif.joins(:gif_statistics).where(...)。我想根据liked gif_statistics or disliked`的计数来订购此查询,例如

伪代码

Gif.joins(:gif_statistics).where(...).order("gifs.gifs_statistics.where(state: "liked").count)")

我尝试应用sort方法,但这不起作用。还有什么我可以尝试实现这一目标?此外,我只在where子句

之后按次数排序

2 个答案:

答案 0 :(得分:2)

请让我试试答案。我肯定会在直接SQL中这样做。您可以随时使用数组和映射在Ruby中进行聚合,但这会导致性能不佳。这是你的SQL查询(请更正任何错误,因为我没有你的架构,因此我无法测试它。)

select g.id, s.status, count(s.status) cnt
from gifs g
inner join gif_statistics s
  on g.id = s.gif_id
group by g.id, s.status
order by cnt

现在请参阅此文档以在ruby中运行SQL:

http://guides.rubyonrails.org/active_record_querying.html#finding-by-sql

答案 1 :(得分:0)

试试这个:

string uri = "http://yts.to/api/v2/list_movies.json?limit=20&page=1";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse();
   if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
   {
      var root = JsonConvert.DeserializeObject<RootObject>("/list_movies.json");
      var articles = root.data.movies.Select(m => new Article { Name = m.title, ImagePath = m.medium_cover_image, Year = m.year.ToString() }).ToList();        
   }
   else
   {
       var dialog = new MessageDialog("Their seems to be a problem retrieving the data...");
       dialog.Title = "Sorry";
   }

此类查询将返回gif_statistics.status订购的Gif。使用DESC或ASC按字母顺序排列喜欢/不喜欢。

相关问题