ccniuj / tilap

Today I Learned And Practiced
16 stars 9 forks source link

What is Single Table Inheritance? #21

Open ccniuj opened 8 years ago

ccniuj commented 8 years ago

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 like Person, Company, and Organization.

Consider we need to implement:

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
LukeHC commented 8 years ago

very interesting. You're using Github to document your learnings!

ccniuj commented 8 years ago

@Luke-H-C It is quite convenient! You should do it as well.