RoR多态关联堆栈级别错误太深

时间:2012-10-22 13:51:55

标签: ruby-on-rails ruby ruby-on-rails-3

我有多态关联,看起来像

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 个答案:

答案 0 :(得分:3)

首先,我认为协会可能是模型名称的不幸选择。

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

我还建议,考虑到上述段落有多难以理解,关联可能不是Rails模型的最佳名称!

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

相关问题