Search code examples
ruby-on-railsdatabase-migrationsingle-table-inheritance

Single Table Inheritance: Optional Plugin module and migrations


I want to know how you can solve this with ruby on rails:

there is a core module which provides a class BasePlugin.

Optional plugins inherits (single table inheritance) from this base class.

Example: The FooPlugin from fooplugin module is a external, optional module (provided by a third party).

Since STI is used the migrations for FooPlugin need to live in the fooplugin module.

Result: BasePlugin does not know its whole table, since optional external modules add extra columns.

I am new to ruby on rails, but have developed database based applications in different languages for years.

Question:

Is the above usage of STI possible with ruby on rails?


Solution

  • The STI table contains the intersection of all attributes for both the parent model and all children models. Note that in STI, BasePlugin is a model, not a module. External plugins are generally provided as gems.

    But the key thing is that BasePlugin doesn't need to have all of it's attributes defined when it is first created. If you later add a FooPlugin child and use a migration to add columns to the base_plugins table to add attributes to FooPlugin, BasePlugin will be able to see those columns. ActiveRecord uses introspection to populate the database columns into the ActiveRecord object at startup, so BasePlugin.attribute_names will show you all columns, even if they are only used by the child type.