2015-05-26 82 views
0

我有型號Gif,其中有has_many gif_statisticsGifStatistic模型有字段status可能的選項:likedislike。 我有像 Gif.joins(:gif_statistics).where(...)查詢。我想訂購這個查詢取決於liked gif_statistics or不喜歡的數量,例如。按關聯表項數排序

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

我試圖申請sort方法,但沒有奏效。我還有什麼可以嘗試做到這一點?此外,我只有通過計數訂單後where條款

+0

爲了這個查詢。沒有得到你..顯示你的完整查詢.. –

回答

0

試試這個:

Gif.joins(:gif_statistics).where(...).order('gif_statistics.status DESC') 

這樣的查詢將返回gif_statistics.status訂購照片與圖像。按照喜歡/不喜歡的字母順序使用DESC或ASC。

1

請讓我試試答案。我一定會用直接的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 

現在看到這個文檔,以紅寶石運行SQL:根據任尤其愛吃gif_statisticsordisliked計數

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