[英]Associate foreign key through another foreign key
I've these 3 Models 我有这三个模型
class User < ActiveRecord::Base
has_many :answers, :as => :owner
end
class Answer < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
has_one :test
end
class Test < ActiveRecord::Base
belongs_to :answer
end
so I want to associate the Test
model with User
model through Answer
Model without need of creating new association between them, so I put the following into Test Model: 因此我想通过Answer
模型将Test
模型与User
模型相关联,而无需在它们之间创建新的关联,因此我将以下内容放入测试模型中:
has_one :owner, :through => :answer
but it doesn't work and I got this error 但它不起作用,我得到了这个错误
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError: Cannot have a has_many :through association 'Test#owner' on the polymorphic object 'Owner#owner'.
any help? 有什么帮助吗?
在Test
:
delegate :owner, :to => :answer
You have to specify source_type
option as owner
is a polymorphic association 您必须指定source_type
选项,因为owner
是多态关联
class Test < ActiveRecord::Base
belongs_to :answer
has_one :owner, :through => :answer, :source_type => "User"
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.