has_many 在 has_many 之后:通过?

has_many after a has_many :through?

这是我当前的模型...

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

我希望能够为用户获取所有 Albums

我可以很容易地找到艺术家 (@user.artists),但我很难得到这些艺术家的所有专辑。

Artists 通过 Follows 模型与 Users 关联。

希望能够做 @users.albums@users.artists.albums 之类的事情。

您有 user has_many :artistsartist has_many :albums

只需在 User 模型中与 album :through artists

创建一个 has_many 关联
class User < ApplicationRecord
  has_many :follows
  has_many :artists, -> { uniq }, through: :follows
  has_many :album, through: :artists
end

现在您可以使用@user.albums