0

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?

guettli
  • 25,042
  • 81
  • 346
  • 663

2 Answers2

1

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.

Dan Kohn
  • 33,811
  • 9
  • 84
  • 100
0

Yes you can implement what you describe, as ActiveRecord loads the schema after it connects to the database.

I have written about "best practices" using STI with Rails + ActiveRecord on another stackoverflow question here which might be helpful.

For your use case you will want to make sure plugins don't clash their columns, so you will probably need some kind of column naming scheme/prefix for each plugin.

I no longer use ActiveRecord with Rails, and prefer the more powerful and more performant data access layer Sequel. If you're not locked into ActiveRecord you may want to consider Sequel as an alternative as it supports both STI and also CTI (Class Table Inheritence) as well as the latest Postgres features like JSONB which may be better suited to your use case to keep plugins from clashing with each others columns, or simply just storing your plugin related data in a fully indexed JSON column.

Community
  • 1
  • 1
Andrew Hacking
  • 6,296
  • 31
  • 37