Avdept
Avdept

Reputation: 2289

Rails order by count on association

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

Answers (1)

coderhs
coderhs

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

Related Questions