Reputation: 5073
I have a trailers
table. A Trailer belongs_to a Movie. A Movie has_many Notifications. A Trailer has_many Notifications :through
Movies.
I want to order the Trailers by the number of their notifications. I've tried a few different queries (that haven't worked) and I feel like I'm overcomplicating it.
Can someone help start me off?
Upvotes: 0
Views: 27
Reputation: 5073
Here's what I ended up landing on:
Trailer.joins(:movie => :notifications).
select('trailers.*, COUNT(notifications.id) AS notifications_count').
joins(:movie).group('trailers.id').
order('notifications_count DESC')
Upvotes: 0