我在设置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'.
我认为这个问题与我将用户关系称为:负责人的事实有关。这是对的吗?
非常感谢任何帮助,谢谢。
答案 0 :(得分:11)
感谢@ Abid的评论,我考虑了为用户提供所有responsibilities
的物流,这是不可行的。我需要更加具体地说明我想从关系中获得什么,并且结果定义了以下工作:
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, :foreign_key => :responsible_id
has_many :milestone_responsibilities, :through => :responsible_items, :source => :responsibility, :source_type => 'Milestone'
has_many :task_responsibilities, :through => :responsible_items, :source => :responsibility, :source_type => 'Task'
end