首页 > 解决方案 > 为什么rails不能提供has_and_belongs_to_many多态关联

问题描述

Rails 允许多态关联和 has_and_belongs_to_many / has_many :through 关联;但似乎没有在一起——或者至少很好。

示例设置:

Competition
  has_many :contestants, through: :competition_competitors

CompetitionContestant
  belong_to :competition
  belongs_to :contestant, :polymorphic: true

FootballTeam
  has_many :competitions, as: :contestant, through: :competition_contestants
RugbyTeam
  has_many :competitions, as: :contestant, through: :competition_contestants
Singer
  has_many :competitions, as: :contestant, through: :competition_contestants

解决方案

您指定了 source_type,但随后您必须维护一个感觉不到 RAILSy 的相关多态类的列表。

  has_many :football_teams through: :competition_contestants, source_type: :contestant, source_class: "FootballTeam"
  has_many :rugby_players through: :competition_contestants, source_type: :contestant, source_class: "RugbyTeam"
  has_many :singers through: :competition_contestants, source_type: :contestant, source_class: "Singer"

或者

您可以与中介建立关联并创建自己的功能。但是你并没有得到所有的收集方法/运算符 has_many :through 提供。例如

Competition
  def contestants
    competition_contestants.map(&:contestants)

rails 不允许 has_many :through 与多态类的关联是否有充分的理由?如果 type 和 id 存储在中介中,为什么不能推断 has_many :through 声明中关联了哪些类?

标签: ruby-on-railspolymorphic-associations

解决方案


推荐阅读