Using dynamically created classes in a Single Tabl

2019-08-10 00:58发布

问题:

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

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

Is it possible what I'm trying to accomplish?

Is there something else that needs to be done?

回答1:

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

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

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

@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

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

Personnally, I would do someting like

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