Reputation: 2289
I have 2 models. Gif, GifStatistic
gif has_many :gif_statistics
GifStatistics
has column called state
. It can be either like
or dislike
What i want to achieve is to query gifs, but order them in highest count of likes
Something like(Pseudo code)
Gif.joins(:gif_statistics).order(count(gif.gif_statistics.state))
How do i achieve this?
Upvotes: 2
Views: 1214
Reputation: 4867
Try this query.
Gif.joins(:gif_statistics).select("*, count(gif_statistics.state) as state_count").order("state_count desc")
My personal recommendation is that you create two new fields in the gif model so that you can store the count of like and dislike as and when its created so that you don't have to do such a complex query. Placing the counter cache would improve the speed.
Upvotes: 2