我有一个问题设置Rails has_many:通过:多态关系.
我知道这个主题是well documented,但我认为我的问题归结为我的模型和foreign_key名称而不是语法,即我认为这是“我一直在看代码太长”的问题,只需要另一个一双眼睛.
无论如何,我有以下设置:
class Milestone < ActiveRecord::Base has_many :responsible_items,:as => :responsibility has_many :responsible,:through => :responsible_items end class ResponsibleItem < ActiveRecord::Base belongs_to :responsible,:class_name => "User" belongs_to :responsibility,:polymorphic => true end class User < ActiveRecord::Base has_many :responsible_items,:foreign_key => :responsible_id has_many :responsibilities,:through => :responsible_items end
从里程碑方面看,这似乎没有错误.例如在终端我可以写:
Milestone.first.responsible
……按照我的预期得到一个空集合.
但是,从用户方面来说,运行:
User.first.responsibilities
…正在返回AR错误:
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError: Cannot have a has_many :through association 'User#responsibilities' on the polymorphic object 'Responsibility#responsibility'.
我假设这个问题与我将用户关系称为:负责人这一事实有关.这是正确的吗?
任何帮助将不胜感激,谢谢.
解决方法
感谢@ Abid的评论,我考虑了为用户承担所有责任的后勤工作,这是不可行的.我需要更加具体地说明我想从关系中得到什么,并且结果定义了以下工作:
class User < ActiveRecord::Base has_many :responsible_items,:foreign_key => :responsible_id has_many :milestone_responsibilities,:through => :responsible_items,:source => :responsibility,:source_type => 'Milestone' end
然后,我可以扩展它,因为我在其他模型上添加了更多的多态关系,例如:
class User < ActiveRecord::Base has_many :responsible_items,:source_type => 'Milestone' has_many :task_responsibilities,:source_type => 'Task' end