Shpigford
Shpigford

Reputation: 25378

has_many after a has_many :through?

Here are my current models...

class Artist < ApplicationRecord
  has_many :albums
  has_many :follows
  has_many :users, -> { uniq }, through: :follows
end

class Album < ApplicationRecord
  belongs_to :artist
end

class Follow < ApplicationRecord
  belongs_to :artist
  belongs_to :user
end

class User < ApplicationRecord
  has_many :follows
  has_many :artists, -> { uniq }, through: :follows
end

What I want to be able to do is get all the Albums for a user.

I can get the artists easily (@user.artists) but what I'm having trouble getting are all the albums of those artists.

Artists are associated with Users through the Follows model.

Would love to be able to do something like @users.albums or @users.artists.albums.

Upvotes: 1

Views: 45

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23711

You have user has_many :artists and artist has_many :albums

Just create a has_many association in User model with album :through artists

class User < ApplicationRecord
  has_many :follows
  has_many :artists, -> { uniq }, through: :follows
  has_many :album, through: :artists
end

Now you can use @user.albums

Upvotes: 1

Related Questions