在单表继承机制中使用动态创建的类 [英] Using dynamically created classes in a Single Table Inheritance mechanism

查看:74
本文介绍了在单表继承机制中使用动态创建的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为'DynObject'的ActiveRecord类,该类可用于继承。

I have an ActiveRecord class called 'DynObject' which can be used for inheritance..

在初始化时,我会动态创建一些从其继承的类:

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

这些类都很好创建就好了。但是当ActiveRecord尝试加载创建的记录时,STI机制失败。。(ActiveRecord :: SubclassNotFound(单表继承机制无法找到子类:'FooObject'... ))

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'....))

我认为这很奇怪,因为当我检查类时在中如何命名它们类型列,它们就存在。

Which I think is weird, because when I inspect the classes as how they are named in the type column, they exist..

当我检查这些类的祖先时他们也继承得很好。

When I check the ancestors of these classes they also inherit just fine..

是否有可能我要完成?

推荐答案

您的错误消息表明无法找到'FooObject'类。

Your error message stands that 'FooObject' class cannot be located.

在您的代码中,动态g

In your code, the dynamic generated class name shoudl be 'FooDynObject'.

在加载DynObject之前,只需检查数据库中是否没有旧的测试记录即可。

Just check you don't have old test records in your database before loading DynObject.

@edit:
另一件事是还知道影响动态类名的类。

@edit: Another thing is also to know on which class you affect the dynamic class name.

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

将在DynObject :: FooDynObject中生成结果,当ActiveRecord看到 FooDynObject类型时,ActiveRecord将无法加载它。

Will result in DynObject::FooDynObject, and ActiveRecord won't be able to load it when it will see 'FooDynObject' type.

我个人会这样做像

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

这篇关于在单表继承机制中使用动态创建的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆