Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Difficult Child <> Parent <> Child (sibling) SQL Query with Rails & Active Record

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

Answers (1)

Jackson Cunningham
Jackson Cunningham

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

Related Questions