两个相似的多对多关系
Two similar Many-to-Many Relationships
我有两个相似的 M:M 关系,我单独处理它们,但我不知道如何在不冲突的情况下处理它们。
关系是球员和球队
1) Many players "play for" many teams
2) Many players "are members of" many teams
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
您必须为每个 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
提示:我更新了答案。
我有两个相似的 M:M 关系,我单独处理它们,但我不知道如何在不冲突的情况下处理它们。
关系是球员和球队
1) Many players "play for" many teams
2) Many players "are members of" many teams
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
您必须为每个 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
提示:我更新了答案。