Paul
Paul

Reputation: 26680

Polymorphic models (not associations!) in Rails

Important

For those who TL;DNR: I am talking not about polymorphic associations.

The question

In object oriented programming I was often using polymorphic business logic data layer classes: one base abstract class and its descendants for specific behaviour.

Now I am thinking whether it is possible to do so in Rails. Currently it seems to be unreal because Rails models are tightly tied to database tables.

Is it possible to have one table for multiple Rails models (with common ancestor) - some fields are common, other are descendant-specific ?

Upvotes: 0

Views: 49

Answers (1)

D-side
D-side

Reputation: 9495

Yep. Single Table Inheritance.

Add a type:string column to a table for a model you wish to inherit from, then create new classes that inherit from your base model (say, Animal). An instance of this class (like, say, Cat) is defined as Animal, whose type is "Cat".

Upvotes: 1

Related Questions