Last active
October 18, 2019 05:17
-
-
Save rankitranjan/84985f335dd043067cd0be402164b82f to your computer and use it in GitHub Desktop.
Single Table Inheritance with Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
has_many :follows | |
delegate :following, :follower, to: :follows | |
end | |
class Follow < ActiveRecord::Base | |
scope :following, -> { where(type: 'following') } | |
scope :follower, -> { where(type: 'follower') } | |
end | |
class Following < Follow | |
# write something which belongs to Following only | |
end | |
class Follower < Follow | |
# write something which belongs to Follower only | |
end | |
STI PROS: | |
Simple to implement | |
DRY — saves replicated code using inheritance and shared attributes | |
Allows subclasses to have own behavior as necessary | |
STI CONS: | |
Doesn’t scale well: as data grows, table can become large and possibly difficult to maintain/query | |
Requires care when adding new models or model fields that deviate from the shared fields | |
(conditional) Allows creation of invalid objects if validations are not in place | |
(conditional) Can be difficult to validate or query if many null values exist in table | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment