Single Table Inheritance in Ruby on Rails

This article will discuss Single Table Inheritance in Ruby on Rails.

Often there are situations where models need to share a single table in the database. For example, building a salon application with a HairDresser model and a BeardDresser model. Separate database tables for the two models aren’t necessary because they share the same attributes - name, gender, age, salary, etc. Fortunately, they can share the same table using STI(Single Table Inheritance). Here is how to implement it.

1
rails new single-table-inheritance
1
2
rails generate model Expert name gender salary type
rails db:create db:migrate 
1
2
3
4
# app/models/beard_dresser.rb

class BeardDresser < Expert
end
1
2
3
4
# app/models/hair_dresser.rb

class HairDresser < Expert
end
1
2
3
4
5
6
7
8
9
10
11
HairDresser.create(name: "John", gender: "male", salary: "10000")
BeardDresser.create(name: "Mike", gender: "male", salary: "9000")

HairDresser.count
=> 1

BeardDresser.count
=> 1

Expert.count
=> 2

There you have it! Now you know how models can share a table in a database.