Skip to content

Instantly share code, notes, and snippets.

@rankitranjan
Last active October 18, 2019 05:17
Show Gist options
  • Save rankitranjan/84985f335dd043067cd0be402164b82f to your computer and use it in GitHub Desktop.
Save rankitranjan/84985f335dd043067cd0be402164b82f to your computer and use it in GitHub Desktop.
Single Table Inheritance with Rails
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