ruby-on-rails - 为什么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 声明中关联了哪些类?
解决方案
推荐阅读
- java - 运行spring boot项目时出现错误
- android - 二进制 XML 文件第 2 行:膨胀类 android.widget.RelativeLayout 时出错
- python - 如何将不同长度的字典列表转换成excel?
- python - 如何使用 Pandas 从多列中确定最大值
- typescript - Typescript - Intellisense 没有正确建议导入的模块属性
- python - 如何使用正则表达式将特定子字符串提取到新行中?
- angular - TypeError:无法读取未定义的属性“获取”(修复冲突导入不起作用)
- chocolatey - 安装 Chocolatey 包时发生包检索错误
- python - 用于 Python 文本处理的类 CPP 功能
- java - 我不明白我在将 toString 与我的 UI 混合时遇到的问题