Single Table Inheritance (STI) is a technique of mapping inherited classes to a single relational database table.
Why and when should we use it?
Imagine that you have a ActiveRecord model Contact, and it stores 3 different types of contacts like Person, Company, and Organization.
Consider we need to implement:
Validate presence of Person's email
Validate presence of Company's address
Validate presence of Organization's phone number
How can we do it in Contct model? This task can be achieved by using STI.
How to use STI?
First, add a column type to table contacts, where type is a reserved keyword for STI:
class AddTypeToContact < ActiveRecord::Migration
def change
add_column :contacts, :type, :string
end
end
Next, we create class for each type of contact. We can move validations to specific class:
class Contact < ActiveRecord::Base
end
class Person < Contact
validates :email, presence: true
end
class Company < Contact
validates :address, presence: true
end
class Organization < Contact
validates :phone_number, presence: true
end
Finally, we can create instance of these classes:
p = Person.create email: 'foo@example.com'
p.type # => Person
c = Company.create address: 'Foobar Rd.'
c.type # => Company
o = Organization.create phone_number: '0211112222'
o.type # => Organization
ref: Martin Fowler ref: Rails API doc ref: ihower
What is Single Table Inheritance?
Single Table Inheritance (STI) is a technique of mapping inherited classes to a single relational database table.
Why and when should we use it?
Imagine that you have a ActiveRecord model
Contact
, and it stores 3 different types of contacts likePerson
,Company
, andOrganization
.Consider we need to implement:
Person
's emailCompany
's addressOrganization
's phone numberHow can we do it in
Contct
model? This task can be achieved by using STI.How to use STI?
First, add a column
type
to tablecontacts
, wheretype
is a reserved keyword for STI:Next, we create class for each type of contact. We can move validations to specific class:
Finally, we can create instance of these classes: