0

私は2つの同様のM:M関係を持っていますが、私は個別に作業しますが、矛盾することなく作業する方法はわかりません。2つの似たような多対多の関係

の関係は、私は多くの選手が

class Player < ActiveRecord::Base 
    has_many :plays 
    has_many :members 
    has_many :teams, through: :plays 
    has_many :teams, through: :members 
end 

class Teams < ActiveRecord::Base 
    has_many :plays 
    has_many :members 
    has_many :players, through: :plays 
    has_many :players, through: :members 
end 

class Play < ActiveRecord::Base 
    belongs_to :players 
    belongs_to :teams 
end 

class Member < ActiveRecord::Base 
    belongs_to :players 
    belongs_to :teams 
end 

多くのチーム "のメンバーである" &チーム

1多くのチーム

2)多くの選手 "のための遊び")選手です見つけることができる必要があります:

Player.find(21).teams #who he plays for 
Player.find(21).teams #who he is a member of 

答えて

1

has_manyアソシエーションに異なる名前を付け、sourceパラメータを使用して実際のアソシエーション名を指定する必要があります。このよう

:このように使用することができます

class Player < ActiveRecord::Base 
    has_many :plays 
    has_many :memberships 
    has_many :played_with_teams, through: :plays, source: :team 
    has_many :member_of_teams, through: :memberships, source: :team 
end 

class Team < ActiveRecord::Base 
    has_many :plays 
    has_many :memberships 
    has_many :played_players, through: :plays, source: :player 
    has_many :member_players, through: :members, source: :player 
end 

class Play < ActiveRecord::Base 
    belongs_to :player 
    belongs_to :team 
end 

class Membership < ActiveRecord::Base 
    belongs_to :player 
    belongs_to :team 
end 

Player.find(21).played_with_teams #who he plays for 
Player.find(21).member_of_teams #who he is a member of 

ヒント:私は答えを更新しました。

+0

class_name: 'チーム'とソース: 'チーム'の違いは何ですか? – Dercni

+0

これをチェックアウトすると、その違いに関する説明が表示されます。https://stackoverflow.com/q/13611265/368167 –