SlideShare a Scribd company logo
1 of 22
Download to read offline
Single Table Inheritance (STI) 
Raul Pristopan 
1 / 22
Agenda 
1. Introduction 
2. What is STI? 
3. When should we use STI? 
4. How do we implement STI? 
5. Reasons why you shouldn't use STI 
6. Demo 
2 / 22
Introduction 
3 / 22
Introduction 
In the beginning everything always works. Things get complicated with 
time when you start adding new features. 
Some weeks ago I had to refactor some parts of a project and also add 
some new features to it. 
After some hours of reviewing the actual code I run into some problems: 
1. Same code in multiple places 
2. Same data stored in 2 or more tables 
create_table "users", :force => true do |t| 
... 
t.string "image_file_name" 
t.string "image_content_type" 
t.integer "image_file_size" 
t.datetime "image_updated_at" 
... 
4 / 22
Introduction 
create_table "activities", :force => true do |t| 
... 
t.string "image_file_name" 
t.string "image_content_type" 
t.integer "image_file_size" 
t.datetime "image_updated_at" 
... 
create_table "image_attachments", :force => true do |t| 
t.string "image_file_name" 
t.string "image_content_type" 
t.integer "image_file_size" 
t.datetime "image_updated_at" 
t.datetime "created_at", :null => false 
t.datetime "updated_at", :null => false 
t.integer "used_by_count", :default => 1 
t.text "original_url" 
end 
5 / 22
What is STI? 
STI is basically the idea of using a single table to reflect multiple models 
that inherit from a base model, which itself inherits from 
ActiveRecord::Base. 
In the database schema, sub-models are indicated by a single "type" 
column. 
In other words we have: 
a base class 
descendant classes 
6 / 22
When should we use STI? 
Should be considered when dealing with model classes that share much of 
the same functionality and data fields (granular control over extending or 
adding to each class individually) 
When you have duplicate code over and over for multiple tables (and not 
being DRY) 
STI permits you to use keep your data in a single table while writing 
specialized functionality. 
7 / 22
When should we use STI? 
Suppose you have three classes in your application which model similar 
things. To make this easier to think about I’ll be referring to some hypothetical 
classes by name: Business and Employee. Let’s consider three choices for 
modeling this situation: 
1. Polymorphic Associations (separate classes, multiple tables) 
2. Single Table Inheritance (separate classes, one table) 
3. Single Class with conditionals (one class, one table) 
8 / 22
When should we use STI? 
Polymorphic Associations (separate classes, multiple tables) 
With Polymorphic Associations we use modules to share code among 
classes. 
We have the following active record models for a “Business” and an 
“Employee”. 
class Business < ActiveRecord::Base 
# Methods, variables and constants 
end 
class Employee < ActiveRecord::Base 
# Methods, variables and constants 
end 
9 / 22
When should we use STI? 
Polymorphic Associations (separate classes, multiple tables) 
For the contact information, we have the following active record models: 
class PhoneNumber < ActiveRecord::Base 
# Methods, variables and constants 
end 
class Website < ActiveRecord::Base 
# Methods, variables and constants 
end 
10 / 22
When should we use STI? 
Polymorphic Associations (separate classes, multiple tables) 
Now, for the associations, Business and Employee models can have many 
phone numbers and websites. And conversely, Phone Number/Website can 
belong to either a Business model or an Employee model. 
class Business < ActiveRecord::Base 
has_many :phone_numbers, :as => phonable 
has_many :websites, :as => webable 
end 
class Employee < ActiveRecord::Base 
has_many :phone_numbers, :as => phonable 
has_many :websites, :as => webable 
end 
11 / 22
When should we use STI? 
Polymorphic Associations (separate classes, multiple tables) 
class PhoneNumber < ActiveRecord::Base 
belongs_to :phonable, :polymorphic => true 
end 
class Website < ActiveRecord::Base 
belongs_to :webable, :polymorphic => true 
end 
Having the above setup, you can get a collection of phone numbers for a 
business instance via the call “@business.phone_numbers. 
Similarly, you can get a collection of phone numbers for an employee instance 
via “@employee.phone_numbers”. 
12 / 22
When should we use STI? 
Single Class with conditionals (one class, one table) 
A Single Class is not exactly a design pattern, or anything particularly 
interesting. 
I’m thinking of a model with a type-like attribute (maybe called kind) and 
some if statements in methods where you need different behavior for 
different kinds of objects. 
13 / 22
When should we use STI? 
Questions to ask yourself 
When deciding how to design your data models, here are some questions to 
ask yourself: 
1. Are the objects, conceptually, children of a single parent? 
2. Do you need to do database queries on all objects together? 
3. Do the objects have similar data but different behavior? 
14 / 22
How do we implement STI? 
Create the base class 
Model: Employee 
Attributes: 
Name - String 
Age - Integer 
Department - String 
$ rails generate model Employee name:string age:integer department:string 
# /app/models/employee.rb 
class Employee < ActiveRecord::Base 
# Methods, variables and constants 
end 
15 / 22
How do we implement STI? 
Add a :type attribute as a string to the base class 
$ rails generate migration add_type_to_employee type:string 
16 / 22
How do we implement STI? 
Create any necessary descendant classes 
# /app/models/developer.rb 
class Developer < Employee 
# Methods, variables and constants 
end 
# /app/models/tester.rb 
class Tester < Employee 
# Methods, variables and constants 
end 
17 / 22
Reasons why you shouldn't use STI 
It creates a cluttered data model 
Why don’t we just have one table called objects and store everything as 
STI? 
STI tables have a tendency to grow and expand as an application develops, 
and become intimidating and unweildy as it isn’t clear which columns 
belong to which models. 
18 / 22
Reasons why you shouldn't use STI 
It forces you to use nullable columns 
If sub-classes that you intend to use for STI have many different data 
fields, then including them all in the same table would result in a lot of 
null values and make it difficult to scale over time. In this case, you may 
end up with so much code in your model sub-classes that the shared 
functionality between sub-classes is minimal and warrants separate 
tables. 
A comic book must have an illustrator, but regular books don’t have an 
illustrator. 
Subclassing Book with Comic using STI forces you to allow illustrator to be 
null at the database level (for books that aren’t comics), and pushes your 
data integrity up into the application layer, which is not ideal. 
19 / 22
Reasons why you shouldn't use STI 
It prevents you from efficiently indexing your data 
Every index has to reference the type column, and you end up with 
indexes that are only relevant for a certain type. 
20 / 22
Reasons why you shouldn't use STI 
Two objects types have similar attributes 
Both airplanes and bicycles have wheels, but it probalby doesn’t make 
sense to group them into the same table, given that intuitively, they’re 
different objects that will have vastly different functionality and data 
fields in an application. 
Demo 
21 / 22
Thank you! 
22 / 22

More Related Content

What's hot

Applications: Word-Processing, Spreadsheet & Database
Applications: Word-Processing, Spreadsheet & DatabaseApplications: Word-Processing, Spreadsheet & Database
Applications: Word-Processing, Spreadsheet & DatabaseAlaa Sadik
 
20 Unique Uses of Excel Spreadsheets
20 Unique Uses of Excel Spreadsheets20 Unique Uses of Excel Spreadsheets
20 Unique Uses of Excel SpreadsheetsNick Weisenberger
 
Lesson 4 advance spreadsheets skills cost of ingredients.xlsx.
Lesson 4 advance spreadsheets skills cost of ingredients.xlsx.Lesson 4 advance spreadsheets skills cost of ingredients.xlsx.
Lesson 4 advance spreadsheets skills cost of ingredients.xlsx.EmmanuelaSernicul
 
Ms excel and it’s function
Ms excel and it’s functionMs excel and it’s function
Ms excel and it’s functionsneha94
 
CCPRO 2016 Power Presentation
CCPRO 2016 Power PresentationCCPRO 2016 Power Presentation
CCPRO 2016 Power PresentationDavid Onder
 
Murach: ASP.NET Core MVC, How To Work With Razor Views
Murach: ASP.NET Core MVC, How To Work With Razor ViewsMurach: ASP.NET Core MVC, How To Work With Razor Views
Murach: ASP.NET Core MVC, How To Work With Razor ViewsMahmoudOHassouna
 
Starting With Microsoft Excel
Starting With Microsoft ExcelStarting With Microsoft Excel
Starting With Microsoft ExcelKarla P. Corral
 
Mapping inheritance structures_mapping_class
Mapping inheritance structures_mapping_classMapping inheritance structures_mapping_class
Mapping inheritance structures_mapping_classTodor Kolev
 
FEATURES OF MICROSOFT EXCEL
FEATURES OF MICROSOFT EXCELFEATURES OF MICROSOFT EXCEL
FEATURES OF MICROSOFT EXCELpawa9pawa
 
L4 advanced spreadsheet skills
L4 advanced spreadsheet skillsL4 advanced spreadsheet skills
L4 advanced spreadsheet skillsrowenick
 
Ms excel 2013 data management
Ms excel 2013 data managementMs excel 2013 data management
Ms excel 2013 data managementJesus Obenita Jr.
 
Introduction to excel - application to statistics
Introduction to excel - application to statisticsIntroduction to excel - application to statistics
Introduction to excel - application to statisticszavenger
 
Elementary Data Analysis with MS Excel_Day-6
Elementary Data Analysis with MS Excel_Day-6Elementary Data Analysis with MS Excel_Day-6
Elementary Data Analysis with MS Excel_Day-6Redwan Ferdous
 

What's hot (20)

VBA
VBAVBA
VBA
 
Learn about excel
Learn about excelLearn about excel
Learn about excel
 
Applications: Word-Processing, Spreadsheet & Database
Applications: Word-Processing, Spreadsheet & DatabaseApplications: Word-Processing, Spreadsheet & Database
Applications: Word-Processing, Spreadsheet & Database
 
Ms excel ppt
Ms excel pptMs excel ppt
Ms excel ppt
 
20 Unique Uses of Excel Spreadsheets
20 Unique Uses of Excel Spreadsheets20 Unique Uses of Excel Spreadsheets
20 Unique Uses of Excel Spreadsheets
 
Lesson 4 advance spreadsheets skills cost of ingredients.xlsx.
Lesson 4 advance spreadsheets skills cost of ingredients.xlsx.Lesson 4 advance spreadsheets skills cost of ingredients.xlsx.
Lesson 4 advance spreadsheets skills cost of ingredients.xlsx.
 
Ms excel and it’s function
Ms excel and it’s functionMs excel and it’s function
Ms excel and it’s function
 
CCPRO 2016 Power Presentation
CCPRO 2016 Power PresentationCCPRO 2016 Power Presentation
CCPRO 2016 Power Presentation
 
Murach: ASP.NET Core MVC, How To Work With Razor Views
Murach: ASP.NET Core MVC, How To Work With Razor ViewsMurach: ASP.NET Core MVC, How To Work With Razor Views
Murach: ASP.NET Core MVC, How To Work With Razor Views
 
Starting With Microsoft Excel
Starting With Microsoft ExcelStarting With Microsoft Excel
Starting With Microsoft Excel
 
Mapping inheritance structures_mapping_class
Mapping inheritance structures_mapping_classMapping inheritance structures_mapping_class
Mapping inheritance structures_mapping_class
 
Learn Excel 2016 VBA and Macros in 24 Hours (Part 2 of 2) On Practical's Asp...
Learn Excel 2016 VBA and Macros in 24 Hours  (Part 2 of 2) On Practical's Asp...Learn Excel 2016 VBA and Macros in 24 Hours  (Part 2 of 2) On Practical's Asp...
Learn Excel 2016 VBA and Macros in 24 Hours (Part 2 of 2) On Practical's Asp...
 
FEATURES OF MICROSOFT EXCEL
FEATURES OF MICROSOFT EXCELFEATURES OF MICROSOFT EXCEL
FEATURES OF MICROSOFT EXCEL
 
L4 advanced spreadsheet skills
L4 advanced spreadsheet skillsL4 advanced spreadsheet skills
L4 advanced spreadsheet skills
 
Ms excel 2013 data management
Ms excel 2013 data managementMs excel 2013 data management
Ms excel 2013 data management
 
Spreadsheets
SpreadsheetsSpreadsheets
Spreadsheets
 
Introduction to excel - application to statistics
Introduction to excel - application to statisticsIntroduction to excel - application to statistics
Introduction to excel - application to statistics
 
Vba primer
Vba primerVba primer
Vba primer
 
Microsoft excel
Microsoft excelMicrosoft excel
Microsoft excel
 
Elementary Data Analysis with MS Excel_Day-6
Elementary Data Analysis with MS Excel_Day-6Elementary Data Analysis with MS Excel_Day-6
Elementary Data Analysis with MS Excel_Day-6
 

Similar to Rupicon 2014 Single table inheritance

Create a sql script containing your data definition language (ddl)
Create a sql script containing your data definition language (ddl)Create a sql script containing your data definition language (ddl)
Create a sql script containing your data definition language (ddl)RAJU852744
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Luis Valencia
 
Mapping objects to_relational_databases
Mapping objects to_relational_databasesMapping objects to_relational_databases
Mapping objects to_relational_databasesIvan Paredes
 
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...Karen Thompson
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Single sourcing to the max
Single sourcing to the maxSingle sourcing to the max
Single sourcing to the maxNeil Perlin
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net coreSam Nasr, MCSA, MVP
 
Poject documentation deepak
Poject documentation deepakPoject documentation deepak
Poject documentation deepakchetankane
 
How to do code review and use analysis tool in software development
How to do code review and use analysis tool in software developmentHow to do code review and use analysis tool in software development
How to do code review and use analysis tool in software developmentMitosis Technology
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010vchircu
 
Teradata Aggregate Join Indices And Dimensional Models
Teradata Aggregate Join Indices And Dimensional ModelsTeradata Aggregate Join Indices And Dimensional Models
Teradata Aggregate Join Indices And Dimensional Modelspepeborja
 
20 tips and tricks with the Autonomous Database
20 tips and tricks with the Autonomous Database20 tips and tricks with the Autonomous Database
20 tips and tricks with the Autonomous DatabaseSandesh Rao
 
Related Worksheets
Related WorksheetsRelated Worksheets
Related WorksheetsEirik Bakke
 

Similar to Rupicon 2014 Single table inheritance (20)

Sda 9
Sda   9Sda   9
Sda 9
 
Create a sql script containing your data definition language (ddl)
Create a sql script containing your data definition language (ddl)Create a sql script containing your data definition language (ddl)
Create a sql script containing your data definition language (ddl)
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
 
Mapping objects to_relational_databases
Mapping objects to_relational_databasesMapping objects to_relational_databases
Mapping objects to_relational_databases
 
Mvp pattern
Mvp patternMvp pattern
Mvp pattern
 
Sql Lab 4 Essay
Sql Lab 4 EssaySql Lab 4 Essay
Sql Lab 4 Essay
 
Ad507
Ad507Ad507
Ad507
 
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
Single sourcing to the max
Single sourcing to the maxSingle sourcing to the max
Single sourcing to the max
 
CS8592-OOAD Question Bank
CS8592-OOAD  Question BankCS8592-OOAD  Question Bank
CS8592-OOAD Question Bank
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net core
 
Poject documentation deepak
Poject documentation deepakPoject documentation deepak
Poject documentation deepak
 
How to do code review and use analysis tool in software development
How to do code review and use analysis tool in software developmentHow to do code review and use analysis tool in software development
How to do code review and use analysis tool in software development
 
Sq lite module2
Sq lite module2Sq lite module2
Sq lite module2
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Teradata Aggregate Join Indices And Dimensional Models
Teradata Aggregate Join Indices And Dimensional ModelsTeradata Aggregate Join Indices And Dimensional Models
Teradata Aggregate Join Indices And Dimensional Models
 
20 tips and tricks with the Autonomous Database
20 tips and tricks with the Autonomous Database20 tips and tricks with the Autonomous Database
20 tips and tricks with the Autonomous Database
 
Tableau training course
Tableau training courseTableau training course
Tableau training course
 
Related Worksheets
Related WorksheetsRelated Worksheets
Related Worksheets
 

More from rupicon

RSpec matchers
RSpec matchersRSpec matchers
RSpec matchersrupicon
 
DIY Cartography
DIY CartographyDIY Cartography
DIY Cartographyrupicon
 
Dr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
Dr. PostGIS or: How I Learned to Stop Worrying and Love the DocsDr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
Dr. PostGIS or: How I Learned to Stop Worrying and Love the Docsrupicon
 
Are you tougher than a boy/girl scout?
Are you tougher than a boy/girl scout?Are you tougher than a boy/girl scout?
Are you tougher than a boy/girl scout?rupicon
 
Johnny Cache
Johnny CacheJohnny Cache
Johnny Cacherupicon
 
U wont bleev wut dis code doez
U wont bleev wut dis code doezU wont bleev wut dis code doez
U wont bleev wut dis code doezrupicon
 
Rupicon 2014 Action pack
Rupicon 2014 Action packRupicon 2014 Action pack
Rupicon 2014 Action packrupicon
 
Rupicon 2014 useful design patterns in rails
Rupicon 2014 useful design patterns in railsRupicon 2014 useful design patterns in rails
Rupicon 2014 useful design patterns in railsrupicon
 
Rupicon 2014 solid
Rupicon 2014 solidRupicon 2014 solid
Rupicon 2014 solidrupicon
 
Rupicon 2014 caching
Rupicon 2014 cachingRupicon 2014 caching
Rupicon 2014 cachingrupicon
 

More from rupicon (10)

RSpec matchers
RSpec matchersRSpec matchers
RSpec matchers
 
DIY Cartography
DIY CartographyDIY Cartography
DIY Cartography
 
Dr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
Dr. PostGIS or: How I Learned to Stop Worrying and Love the DocsDr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
Dr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
 
Are you tougher than a boy/girl scout?
Are you tougher than a boy/girl scout?Are you tougher than a boy/girl scout?
Are you tougher than a boy/girl scout?
 
Johnny Cache
Johnny CacheJohnny Cache
Johnny Cache
 
U wont bleev wut dis code doez
U wont bleev wut dis code doezU wont bleev wut dis code doez
U wont bleev wut dis code doez
 
Rupicon 2014 Action pack
Rupicon 2014 Action packRupicon 2014 Action pack
Rupicon 2014 Action pack
 
Rupicon 2014 useful design patterns in rails
Rupicon 2014 useful design patterns in railsRupicon 2014 useful design patterns in rails
Rupicon 2014 useful design patterns in rails
 
Rupicon 2014 solid
Rupicon 2014 solidRupicon 2014 solid
Rupicon 2014 solid
 
Rupicon 2014 caching
Rupicon 2014 cachingRupicon 2014 caching
Rupicon 2014 caching
 

Recently uploaded

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Rupicon 2014 Single table inheritance

  • 1. Single Table Inheritance (STI) Raul Pristopan 1 / 22
  • 2. Agenda 1. Introduction 2. What is STI? 3. When should we use STI? 4. How do we implement STI? 5. Reasons why you shouldn't use STI 6. Demo 2 / 22
  • 4. Introduction In the beginning everything always works. Things get complicated with time when you start adding new features. Some weeks ago I had to refactor some parts of a project and also add some new features to it. After some hours of reviewing the actual code I run into some problems: 1. Same code in multiple places 2. Same data stored in 2 or more tables create_table "users", :force => true do |t| ... t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" ... 4 / 22
  • 5. Introduction create_table "activities", :force => true do |t| ... t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" ... create_table "image_attachments", :force => true do |t| t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "used_by_count", :default => 1 t.text "original_url" end 5 / 22
  • 6. What is STI? STI is basically the idea of using a single table to reflect multiple models that inherit from a base model, which itself inherits from ActiveRecord::Base. In the database schema, sub-models are indicated by a single "type" column. In other words we have: a base class descendant classes 6 / 22
  • 7. When should we use STI? Should be considered when dealing with model classes that share much of the same functionality and data fields (granular control over extending or adding to each class individually) When you have duplicate code over and over for multiple tables (and not being DRY) STI permits you to use keep your data in a single table while writing specialized functionality. 7 / 22
  • 8. When should we use STI? Suppose you have three classes in your application which model similar things. To make this easier to think about I’ll be referring to some hypothetical classes by name: Business and Employee. Let’s consider three choices for modeling this situation: 1. Polymorphic Associations (separate classes, multiple tables) 2. Single Table Inheritance (separate classes, one table) 3. Single Class with conditionals (one class, one table) 8 / 22
  • 9. When should we use STI? Polymorphic Associations (separate classes, multiple tables) With Polymorphic Associations we use modules to share code among classes. We have the following active record models for a “Business” and an “Employee”. class Business < ActiveRecord::Base # Methods, variables and constants end class Employee < ActiveRecord::Base # Methods, variables and constants end 9 / 22
  • 10. When should we use STI? Polymorphic Associations (separate classes, multiple tables) For the contact information, we have the following active record models: class PhoneNumber < ActiveRecord::Base # Methods, variables and constants end class Website < ActiveRecord::Base # Methods, variables and constants end 10 / 22
  • 11. When should we use STI? Polymorphic Associations (separate classes, multiple tables) Now, for the associations, Business and Employee models can have many phone numbers and websites. And conversely, Phone Number/Website can belong to either a Business model or an Employee model. class Business < ActiveRecord::Base has_many :phone_numbers, :as => phonable has_many :websites, :as => webable end class Employee < ActiveRecord::Base has_many :phone_numbers, :as => phonable has_many :websites, :as => webable end 11 / 22
  • 12. When should we use STI? Polymorphic Associations (separate classes, multiple tables) class PhoneNumber < ActiveRecord::Base belongs_to :phonable, :polymorphic => true end class Website < ActiveRecord::Base belongs_to :webable, :polymorphic => true end Having the above setup, you can get a collection of phone numbers for a business instance via the call “@business.phone_numbers. Similarly, you can get a collection of phone numbers for an employee instance via “@employee.phone_numbers”. 12 / 22
  • 13. When should we use STI? Single Class with conditionals (one class, one table) A Single Class is not exactly a design pattern, or anything particularly interesting. I’m thinking of a model with a type-like attribute (maybe called kind) and some if statements in methods where you need different behavior for different kinds of objects. 13 / 22
  • 14. When should we use STI? Questions to ask yourself When deciding how to design your data models, here are some questions to ask yourself: 1. Are the objects, conceptually, children of a single parent? 2. Do you need to do database queries on all objects together? 3. Do the objects have similar data but different behavior? 14 / 22
  • 15. How do we implement STI? Create the base class Model: Employee Attributes: Name - String Age - Integer Department - String $ rails generate model Employee name:string age:integer department:string # /app/models/employee.rb class Employee < ActiveRecord::Base # Methods, variables and constants end 15 / 22
  • 16. How do we implement STI? Add a :type attribute as a string to the base class $ rails generate migration add_type_to_employee type:string 16 / 22
  • 17. How do we implement STI? Create any necessary descendant classes # /app/models/developer.rb class Developer < Employee # Methods, variables and constants end # /app/models/tester.rb class Tester < Employee # Methods, variables and constants end 17 / 22
  • 18. Reasons why you shouldn't use STI It creates a cluttered data model Why don’t we just have one table called objects and store everything as STI? STI tables have a tendency to grow and expand as an application develops, and become intimidating and unweildy as it isn’t clear which columns belong to which models. 18 / 22
  • 19. Reasons why you shouldn't use STI It forces you to use nullable columns If sub-classes that you intend to use for STI have many different data fields, then including them all in the same table would result in a lot of null values and make it difficult to scale over time. In this case, you may end up with so much code in your model sub-classes that the shared functionality between sub-classes is minimal and warrants separate tables. A comic book must have an illustrator, but regular books don’t have an illustrator. Subclassing Book with Comic using STI forces you to allow illustrator to be null at the database level (for books that aren’t comics), and pushes your data integrity up into the application layer, which is not ideal. 19 / 22
  • 20. Reasons why you shouldn't use STI It prevents you from efficiently indexing your data Every index has to reference the type column, and you end up with indexes that are only relevant for a certain type. 20 / 22
  • 21. Reasons why you shouldn't use STI Two objects types have similar attributes Both airplanes and bicycles have wheels, but it probalby doesn’t make sense to group them into the same table, given that intuitively, they’re different objects that will have vastly different functionality and data fields in an application. Demo 21 / 22