Ruby on rails 两种相似的多对多关系

Ruby on rails 两种相似的多对多关系,ruby-on-rails,activerecord,many-to-many,associations,has-many-through,Ruby On Rails,Activerecord,Many To Many,Associations,Has Many Through,我有两个类似的M:M关系,我单独工作,但我不知道如何在没有冲突的情况下工作 关系是球员和团队 1许多球员为许多球队效力 2许多球员是许多球队的成员 必须为每个具有多个关联的对象指定不同的名称,并使用源参数指定实际的关联名称 像这样: class Player < ActiveRecord::Base has_many :plays has_many :memberships has_many :played_with_teams, through: :plays, source

我有两个类似的M:M关系,我单独工作,但我不知道如何在没有冲突的情况下工作

关系是球员和团队

1许多球员为许多球队效力

2许多球员是许多球队的成员


必须为每个具有多个关联的对象指定不同的名称,并使用源参数指定实际的关联名称

像这样:

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).teams #who he plays for
Player.find(21).teams #who he is a member of
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