SlideShare ist ein Scribd-Unternehmen logo
1 von 58
Downloaden Sie, um offline zu lesen
Data Integrity in Rails
Strategies and techniques to make your data bulletproof
Proactive
Reactive
VS
Simple Complex
Email ValidationsNot NULL constraint
In ApplicationIn Database
Proactive Techniques
NOT NULL Constraint
The “NoMethodError”
@blog.body.to_html
Returns nil
undefined method ‘to_html'
for nil:NilClass
Fix in view
@blog.body.try(:to_html)
Fix in view
@blog.body.to_s.to_html
Fix in view
unless @blog.body.nil?

@blog.body.to_html

end
Learnings
Likely to encounter the same problem in other places
Messy code littered with checks and guards
These are all band-aid fixes
Fix using Rails Validation
validates :body,
presence: true,
if: ->(record) { record.nil? }
WTH?!?
Validations can
still be bypassed
blog = Blog.new

blog.body = nil

blog.save(validate: false)
Learnings
Code is unnecessarily hard to read
Validations can be bypassed, resulting in incoherent data
Fix in Database
change_column :blog, :body, :text,
null: false,
default: ''
Learnings
No Code Modification
Less Complexity–you never have to deal with both
nils and blank strings
Work on the assumption that body is never nil
The missing Parent
The “NoMethodError”
@post.author.name
Returns nil
undefined method ‘name'
for nil:NilClass
Deleting parent but not
children results in this error
Fix in view
@post.author.name if @post.author
Fix in view
@post.author.try(:name)
Learnings
Likely to encounter the same problem in other places
Messy code littered with checks and guards
These are all band-aid fixes
Fix using ActiveRecord
has_one :author,
dependent: :destroy
Fix using ActiveRecord
has_one :author,
dependent: :destroy
Inefficient if lots of records
Fix using ActiveRecord
has_one :author,
dependent: :delete_all
Does only one query,
but doesn’t run callbacks
Fix using ActiveRecord
has_one :author,
dependent: :restrict_with_exception
Blows up if you try to delete a
parent with children in DB
Fix using ActiveRecord
has_one :author,
dependent: :restrict_with_error
Shows an error if you try to delete
a parent with children in DB
These strategies can
still be bypassed
Post.find(1).delete
Learnings
This is better than fixing locally in views
But this can still introduce bad data
Fix in Database
add_foreign_key :authors, :posts
Fix in Database
add_foreign_key :authors, :posts
Rails 4.2 Feature
Fix in Database
ALTER TABLE `authors`

ADD CONSTRAINT `authors_post_id_fk`

FOREIGN KEY (`post_id`) REFERENCES `posts`(id);
Fix in Database
add_foreign_key :authors, :posts,

on_delete: :cascade
Removes all authors
when a post is deleted
Fix in Database
add_foreign_key :authors, :posts,

on_delete: :restrict
:restrict is the
default behavior of foreign keys
Ideal fix
has_one :author,
dependent: :delete_all
add_foreign_key :authors, :posts,

on_delete: :restrict
Learnings
The ideal fix never allows someone to directly introduce
orphan data, but still does the optimized cascading
behavior when deleted in ActiveRecord.
Duplicate Data
Uniqueness Validation
validates :name, uniqueness: true



Author.where(name: "Mr. Duplicate").count

# => 2

Uniqueness Validation
author = Author.new

author.name = "Mr. Duplicate"

author.save(validate: false)
Unique Index
add_index :authors, :name, unique: true
Unique Index
PG::Error: ERROR:
could not create unique index
"index_authors_on_name"

DETAIL: Key (name)=(Mr. Duplicate) is
duplicated.
Ways of Removing Duplicate
Data
Use SQL to arbitrarily remove duplicates
Use scripts to automatically merge content in rows
Manually merge content/remove duplicate rows
Unique Index Protects Data
from having Duplicates
PG::Error: ERROR:
duplicate key value violates unique constraint
"index_authors_on_name"

DETAIL: Key (title)=(Mr. Duplicate) already exists
This error is thrown every time the
Active Record validation is bypassed
Unique Index Protects Data
from having Duplicates
def save_with_retry_on_unique(*args)

retry_on_exception(ActiveRecord::RecordNotUnique) do

save(*args)

end

end
Retries saving when error is thrown,
so the validation can take over
Unique Index Protects Data
from having Duplicates
def save_with_retry_on_unique(*args)

retry_on_exception(ActiveRecord::RecordNotUnique) do

save(*args)

end

end Retries only once
Calls the block only once
One-to-One Relationships
add_index :authors, :name, unique: true
Protects from associating multiple
records to the parent
Learnings
Active Record validations are not meant for data integrity.
Incoherent Data can still be introduced.
Database level index on unique makes sure data is never
duplicated.
Rails will skip validations a lot in concurrent situations, so
always handle the underlying
ActiveRecord::RecordNotUnique Error.
Don’t forget to add unique index on one-to-one relationships.
Polymorphic
Associations
Polymorphic Association
class Post

has_many :comments, as: :commentable

end



class Comment

belongs_to :commentable, polymorphic: true

end
Both commentable_type and
commentable_id are stored in the database.
Polymorphic Association
class Post

has_many :comments, as: :commentable

end



class Comment

belongs_to :commentable, polymorphic: true

end
There is no way to add foreign keys
to polymorphic associations.
Learnings
There is no SQL standard way of adding polymorphic
associations.
Referential Integrity is compromised when we use this
ActiveRecord pattern.
Expensive to index.
The data distribution isn’t usually uniform.
Harder to JOIN in SQL.
Database-friendly
Polymorphic Associations
class Post

has_many :comments, class_name: 'PostComment'

end



class PostComment

include Commentable



belongs_to :post

end
Learnings
Adding one table for each child type maintains data integrity.
Foreign keys can be added.
Extract similar behaviors using modules in Ruby in the
application.
Create a non-table backed Ruby class for creating comments
Use class_name option to designate which class name to
use when retrieving records.
Learnings
Easier to grok and operate.
Harder to aggregate over all comments regardless of type.
More expensive to add another parent type.
Use specific tables if you care for data integrity.
If data integrity is a non-issue, use polymorphic
associations. Event logging or activity feeds are good
examples.
Reactive Techniques
Data Integrity Test Suite
MAX_ERRORS = 50



def test_posts_are_valid

errors = []

Post.find_each do |post|

next if post.valid?



errors << [post.id, post.errors.full_messages]



break if errors.size > MAX_ERRORS

end

assert_equal [], errors

end
Data Integrity Test Suite
def test_post_bodys_are_not_nil

assert_equal 0, Post.where(body: nil).count

end
Learnings
Proactive techniques work best
They’re not always feasible if you have bad data already
Reactive integrity checks are a good alternative
Run these regularly against production data to surface
errors up.
Avoid using complex constraints.
Recap
Not null constraints
Unique indexes
Foreign keys
Refactor Polymorphic association into separate tables
Reactive integrity checks
Thanks!
@rizwanreza

Weitere ähnliche Inhalte

Was ist angesagt?

Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injection
ashish20012
 
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
Christopher Adams
 
Sql injection attacks
Sql injection attacksSql injection attacks
Sql injection attacks
Kumar
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for Android
Jakir Hossain
 

Was ist angesagt? (20)

Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testing
 
Sql injection
Sql injectionSql injection
Sql injection
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injection
 
jQuery plugins & JSON
jQuery plugins & JSONjQuery plugins & JSON
jQuery plugins & JSON
 
Sql injection
Sql injectionSql injection
Sql injection
 
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
seminar report on Sql injection
seminar report on Sql injectionseminar report on Sql injection
seminar report on Sql injection
 
Mvc by asp.net development company in india - part 2
Mvc by asp.net development company in india  - part 2Mvc by asp.net development company in india  - part 2
Mvc by asp.net development company in india - part 2
 
SQL Injections (Part 1)
SQL Injections (Part 1)SQL Injections (Part 1)
SQL Injections (Part 1)
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
Web API with ASP.NET MVC by Software development company in india
Web API with ASP.NET  MVC  by Software development company in indiaWeb API with ASP.NET  MVC  by Software development company in india
Web API with ASP.NET MVC by Software development company in india
 
SQL Injection Attack Detection and Prevention Techniques to Secure Web-Site
SQL Injection Attack Detection and Prevention Techniques to Secure Web-SiteSQL Injection Attack Detection and Prevention Techniques to Secure Web-Site
SQL Injection Attack Detection and Prevention Techniques to Secure Web-Site
 
SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint Presentation
 
Sql injection attacks
Sql injection attacksSql injection attacks
Sql injection attacks
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for Android
 
Understanding advanced blind sqli attack
Understanding advanced blind sqli attackUnderstanding advanced blind sqli attack
Understanding advanced blind sqli attack
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and Security
 

Andere mochten auch

Enabling CD in Enterprises with Testing - Anand Bagmar
Enabling CD in Enterprises with Testing - Anand BagmarEnabling CD in Enterprises with Testing - Anand Bagmar
Enabling CD in Enterprises with Testing - Anand Bagmar
Thoughtworks
 

Andere mochten auch (7)

專題展系統開發
專題展系統開發專題展系統開發
專題展系統開發
 
PG Training
PG TrainingPG Training
PG Training
 
嵌入式平台移植技巧概說
嵌入式平台移植技巧概說嵌入式平台移植技巧概說
嵌入式平台移植技巧概說
 
Enabling CD in Enterprises with Testing - Anand Bagmar
Enabling CD in Enterprises with Testing - Anand BagmarEnabling CD in Enterprises with Testing - Anand Bagmar
Enabling CD in Enterprises with Testing - Anand Bagmar
 
The Dangers of Early Adoption #STC15
The Dangers of Early Adoption #STC15 The Dangers of Early Adoption #STC15
The Dangers of Early Adoption #STC15
 
手機自動化測試和持續整合
手機自動化測試和持續整合手機自動化測試和持續整合
手機自動化測試和持續整合
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and Archives
 

Ähnlich wie Data Integrity in Rails

Vejovis: Suggesting Fixes for JavaScript Faults
Vejovis: Suggesting Fixes for JavaScript FaultsVejovis: Suggesting Fixes for JavaScript Faults
Vejovis: Suggesting Fixes for JavaScript Faults
SALT Lab @ UBC
 
Cool Object Building With PHP
Cool Object Building With PHPCool Object Building With PHP
Cool Object Building With PHP
wensheng wei
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
ARORACOCKERY2111
 

Ähnlich wie Data Integrity in Rails (20)

Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Zend Framework And Doctrine
Zend Framework And DoctrineZend Framework And Doctrine
Zend Framework And Doctrine
 
Intro to Rails 4
Intro to Rails 4Intro to Rails 4
Intro to Rails 4
 
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram ArnoldEfficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Why Our Code Smells
Why Our Code SmellsWhy Our Code Smells
Why Our Code Smells
 
Vejovis: Suggesting Fixes for JavaScript Faults
Vejovis: Suggesting Fixes for JavaScript FaultsVejovis: Suggesting Fixes for JavaScript Faults
Vejovis: Suggesting Fixes for JavaScript Faults
 
Cool Object Building With PHP
Cool Object Building With PHPCool Object Building With PHP
Cool Object Building With PHP
 
Schema plus
Schema plusSchema plus
Schema plus
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Rails and alternative ORMs
Rails and alternative ORMsRails and alternative ORMs
Rails and alternative ORMs
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
Why you shouldn’t edit silver stripe core files (and how to do it anyway)
Why you shouldn’t edit silver stripe core files (and how to do it anyway)Why you shouldn’t edit silver stripe core files (and how to do it anyway)
Why you shouldn’t edit silver stripe core files (and how to do it anyway)
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
 
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram ArnoldEfficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
 
C# interview
C# interviewC# interview
C# interview
 
Rail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendranRail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendran
 
Making Django and NoSQL Play Nice
Making Django and NoSQL Play NiceMaking Django and NoSQL Play Nice
Making Django and NoSQL Play Nice
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress Developer
 

Kürzlich hochgeladen

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Kürzlich hochgeladen (20)

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 

Data Integrity in Rails