【问题标题】:Two similar Many-to-Many Relationships两个相似的多对多关系
【发布时间】:2018-04-04 17:16:51
【问题描述】:

我有两个类似的 M:M 关系,我分别处理它们,但我不知道如何在不冲突的情况下让它们工作。

关系是玩家和团队

1) 许多球员“为”许多球队“效力”

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

【问题讨论】:

    标签: ruby-on-rails activerecord many-to-many associations has-many-through


    【解决方案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
    

    提示:我更新了答案。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-05
    • 2015-03-07
    • 2018-06-09
    • 2014-10-09
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    相关资源
    最近更新 更多