我有多态关联,看起来像
class Certificate < ActiveRecord::Base
attr_accessible :certification_id, :certified_id, :certified_type
belongs_to :certification
belongs_to :certified, :polymorphic => true
end
class Certification < ActiveRecord::Base
attr_accessible :name, :slug
belongs_to :association
end
class Association < ActiveRecord::Base
has_many :certifications
attr_readonly :name, :id
attr_protected :name
end
假设 User
型号
class User < ActiveRecord::Base
has_many :certificates, :as => :certified
end
我试图从多态关联中访问 association
对象
u = User.first
u.certificates
返回 Certificate
的实例数组
u.certificates.first.certification
返回 Certification
的实例
但
u.certificates.first.certification.association
返回 stack level too deep
错误,第二次运行控制台/服务器崩溃 illegal hardware instruction
消息
我确实意识到这个表达式几乎不是代码美的女王,但它应该有效,不应该吗?
1 回答
首先,我认为协会可能是模型名称的不幸选择 .
ActiveRecord :: Base已经有一个名为association的实例方法,您只需通过 Build 与名为Association的模型的关联来覆盖您的认证模型 . 我没有机会准确地追踪到会发生什么,但我猜测一种称为“关联”的方法在反映和操作模型的关联方面可能非常重要,并且覆盖它会产生令人兴奋的后果 .
我还建议,考虑到上面的段落是多么尴尬,因为无论如何,关联可能不是Rails模型的最佳名称!
尝试重命名该模型及其关联,以查看它是否能解决您的问题 .