2016-10-25 6 views
1

は、ここで私が行うことができるようにしたいどのような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は、UsersからFollowsモデルに関連付けられている。

@users.albumsまたは@users.artists.albumsのようなことができるのが大好きです。

答えて

1

あなたが使用することができますuser has_many :artists

artist has_many :albumsはちょうど今album :through artists

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

Userモデルにhas_many関連付けを作成する必要があり@user.albums

関連する問題