Inheritance in Object Programming Concept:

Rails-Single-Table-Inheritance

In OOPS concept, inheritance enables new objects to take on the properties of existing objects. A class that is used as the basis for inheritance is called a superclass or base class. A class that inherits from a superclass is called a subclass or derived class.

Single Table Inheritance(STI) in Rails:

STI uses a single table to represent multiple models that inherit from a base model. In the Rails world, the database schema has a column which specifies the type of model represented by the row. Adding a column named type in a database migration has Rails infer the table uses STI, although the column can be an arbitrary name if you specify the name in the data model. Note that this makes type a reserved word.

Let’s take a example of User model can have multiple addresses,

class User < ActiveRecord::Base 

  has_many :addresses 

end 

class Address < ActiveRecord::Base 

  belongs_to :user 

end 

class BillingAddress < Address 

end 

class ShippingAddress < Address 

end

In the beginning everything always works. Things get complicated with time when you start adding new features. Lets differ the models using few validations for better understandings. In our example ShippingAddress we would like to restrict number of countries.

class Address < ActiveRecord::Base

  validates_presence_of :name, :city, :country

end

class BillingAddress < Address

  validates_presence_of :country

end

class ShippingAddress < Address

  validates_inclusion_of :country, in: %w(UK Canada)

end

Now, checkout the example in rails console,

u = User.new(name: "Ivanka") 

u.save! 

a = u.addresses.build(type: "BillingAddress", name: "Ivanka", city: "Munich", country: "Germany") 

a.save!

Since the type is defined as “Billing Address”, this address details will be considered as data belongs to BillingAddress < Address and cannot be accessed using ShippingAddress.