我有两个类似的M:M关系,我个人合作但是我不知道如何在没有冲突的情况下工作。
关系是玩家&队
1)很多玩家都会玩#34;很多球队
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
我需要能够找到:
Player.find(21).teams #who he plays for
Player.find(21).teams #who he is a member of
答案 0 :(得分: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
提示:我更新了答案。