Shpigford
Shpigford

Reputation: 25338

Rails: How to group by nested association?

I have a Follow model with user_id and track_id. The Track model has an artist_id field.

What I want to do is count which artists have the most followers, but since users follow "tracks" and not "artists", I need to figure out how to do a count through the tracks.

So, what I was thinking was to do some sort of group by on a nested association. i.e. Group the Follow records by "track -> artist_id", somehow.

Then I could count the number of users for each.

Is that even possible? Is there more info that would be useful here?

Upvotes: 0

Views: 1065

Answers (1)

Schwern
Schwern

Reputation: 164809

You need to use has_many :through to establish the Artist <-> Tracks <-> User relationship.

class Artist < ApplicationRecord
  has_many :tracks
  has_many :users, through: :tracks
end

class Follow < ApplicationRecord
  belongs_to :user
  belongs_to :track
end

class Track < ApplicationRecord
  belongs_to :artist
  has_and_belongs_to_many :users, join_table: :follows
end

class User < ApplicationRecord
  has_and_belongs_to_many :tracks
  has_many :artists, through: :tracks, join_table: :follows
end

Then Rails can take care of the joins between Artist and User.

Artist.includes(:users).group(:id).count("users.id")

Upvotes: 2

Related Questions