Skip to content
Belajar membuat single table inheritance pada Rails
Ruby HTML CSS JavaScript CoffeeScript
Branch: master
Clone or download

Latest commit

Fetching latest commit…
Cannot retrieve the latest commit at this time.

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
app
bin
config
db
lib
log
public
storage
test
tmp
vendor
.gitignore
.ruby-version
Gemfile
Gemfile.lock
README.md
Rakefile
config.ru
package.json

README.md

Single Table Inheritance (Coba)

What is Single Table Inheritance?

Single Table Inheritance (STI) is defined as multiple subclasses sharing a single database table. Rails supports STI right out of the box simply by inheriting subclasses from an ActiveRecord parent class which has a type column in its table.

(source: https://medium.com/@User3141592/when-to-use-single-table-inheritance-vs-multiple-table-inheritance-db7e9733ae2e)

Tutorial from: https://www.driftingruby.com/episodes/single-table-inheritance

Prerequisite

  1. Ruby 2.6.3
  2. Rails 5.2.4
  3. PostgreSQL 11.5

Migration

Edit the migration like below

..._create_contacts.rb

class CreateContacts < ActiveRecord::Migration[5.2]
  def change
    create_table :contacts do |t|
      t.integer :user_id
      t.string :type
      t.string :first_name
      t.string :last_name
      t.string :phone_number
      t.string :address
      t.string :city
      t.string :state
      t.date :birthday
      t.timestamps
    end
    add_index :contacts, [:type, :user_id]
  end
end

Models

user.rb

class User < ApplicationRecord
  has_many :emergencies, class_name: 'Emergency'
  has_many :friends, class_name: 'Friend'
end

profile.rb

class Contact < ApplicationRecord
  scope :friends,   -> { where(type: 'Friend') }    # Contact.friends
  scope :emergency, -> { where(type: 'Emergency') } # Contact.emergencies
end

friend.rb*

class Friend < Contact
  belongs_to :user
end

emergency.rb

class Emergency < Contact
  belongs_to :user
end
You can’t perform that action at this time.