From wikipidiea:
“Polymorphic association is a term used in discussions of Object-Relational Mapping with respect to the problem of representing in the relational database domain, a relationship from one class to multiple classes. In statically typed languages such as Java these multiple classes are subclasses of the same superclass. In languages with Duck Typing, such as Ruby, this is not necessarily the case”.
In Rails, ActiveRecord provides you feature by which you can have Polymorphic association (relationship) between two tables without knowing which table will be in the relationship. You can have “XOR” relationships. That is, X can have either of Y or Z, but not both.
There are basically two ways of achieving Polymorphic Association in Rails:
1. Single Table Inheritance (STI)
2. Multiple Table Inheritance (MTI)
Single Table Inheritance
In STI, you can have only one single SQL table to maintain the relationships between two or more different model class of rails.
Let us assume for the explanation purpose, that we want to build a mobile catalogue system. Mobiles are of various types based on their OS, lets categorize our catalogues system based on the OS of mobile.
So our model definitions will be something similar to this:
Mobile Class:
class Mobile < ActiveRecord::Base
end
IOS class:
class IOS < Mobile
end
Android class:
class Android < Mobile
end
In the mobile table, we will have to put a column called "type" to indicate that the table is STI.
The table structure will be something, similar to this:
CREATE TABLE mobiles (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(25) NOT NULL UNIQUE,
price VARCHAR(10) NOT NULL,
type VARCHAR(10) NOT NULL,
PRIMARY KEY (id)
);
The “type” column should store the class names, i.e the class type for each mobile. So in this case, it will be either IOS or Android.
In the next part, we see how we can achieve, Multiple Table Inheritance in rails.