Shpigford Shpigford - 1 month ago 10
Ruby Question

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
.

Answer

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