0

我有看起来像的多态关联

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显示消息

我确实意识到这个表达式很难成为代码美的女王,但它应该有效,不是吗?

4

1 回答 1

3

首先,我认为 Association 可能是一个不幸的模型名称选择。

ActiveRecord::Base 已经有一个名为 Association 的实例方法,您刚刚通过设置与名为 Association 的模型的关联来覆盖您的认证模型。我还没有机会确切地追踪这将要做什么,但我猜一种称为“关联”的方法可能在反思和操作模型的关联方面非常重要,并且覆盖它会产生令人兴奋的结果。

我还建议考虑到上一段读起来有多尴尬,无论如何,Association 可能不是 Rails 模型的最佳名称!

尝试重命名该模型及其关联,看看它是否能解决您的问题。

于 2012-10-22T14:20:59.747 回答