简体   繁体   English

在单表继承机制中使用动态创建的类

[英]Using dynamically created classes in a Single Table Inheritance mechanism

I have an ActiveRecord class called 'DynObject' which can be used for inheritance.. 我有一个称为'DynObject'的ActiveRecord类,该类可用于继承。

On initialization I dynamically create some Classes that inherit from it: 在初始化时,我动态创建一些继承自它的类:

classes_config = { foo: 'foo', bar: 'bar' }

classes_config.each do |name,options|

  klass = Class.new( DynObject ) do

  end

  self.klasses[name] = const_set( "#{name.camelize}DynObject", klass )

end

This is all good, these classes are created just fine.. But when ActiveRecord tries to load created records the STI mechanism failes.. (ActiveRecord::SubclassNotFound (The single-table inheritance mechanism failed to locate the subclass: 'FooObject'....)) 一切都很好,可以很好地创建这些类。但是,当ActiveRecord尝试加载创建的记录时,STI机制将失败。。 (ActiveRecord::SubclassNotFound (The single-table inheritance mechanism failed to locate the subclass: 'FooObject'....))

Which I think is weird, because when I inspect the classes as how they are named in the type column, they exist.. 我认为这很奇怪,因为当我检查类(在type列中的命名方式)时,它们就存在了。

When I check the ancestors of these classes they also inherit just fine.. 当我检查这些类的ancestors ,它们也继承得很好。

Is it possible what I'm trying to accomplish? 我可能要完成什么?

Is there something else that needs to be done? 还有什么需要做的吗?

Your error message stands that 'FooObject' class cannot be located. 您的错误消息表明无法找到'FooObject'类。

In your code, the dynamic generated class name shoudl be 'FooDynObject'. 在您的代码中,动态生成的类名称应为'FooDynObject'。

Just check you don't have old test records in your database before loading DynObject. 只需在加载DynObject之前检查数据库中是否没有旧的测试记录即可。

@edit: Another thing is also to know on which class you affect the dynamic class name. @edit:另一件事是还知道影响动态类名的类。

class DynObject < ActiveRecord::Base
  const_set 'FooDynObject', Class.new(DynObject)
end

Will result in DynObject::FooDynObject, and ActiveRecord won't be able to load it when it will see 'FooDynObject' type. 将导致DynObject :: FooDynObject,并且ActiveRecord在看到“ FooDynObject”类型时将无法加载它。

Personnally, I would do someting like 就个人而言,我会做一些

class DynObject < ActiveRecord::Base
  Object.const_set 'FooDynObject', Class.new(DynObject)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM