What is ActiveRecord's STI vs polymorphic associations — when to use each?
Answer
STI shares one table for multiple subclasses — best when subclasses have the same attributes and differ primarily in behavior. Example: Animal table with Dog and Cat subclasses. Polymorphic associations allow one model to belong to multiple unrelated parent types — best when unrelated models share an associated behavior. Example: both Post and Video can have Comments. Key decision: if subclasses share data structure → STI; if a child model needs to reference multiple unrelated parent types → polymorphic. Neither is ideal for complex hierarchies — consider Multiple Table Inheritance (MTI) via gems or a separate mapping table instead.
Previous
What is optimistic vs pessimistic locking in Rails?
Next
How do you handle background job failures and retries in Rails?
More Ruby on Rails Questions
View all →- Advanced What is metaprogramming in Ruby/Rails and give examples?
- Advanced What is the difference between include, extend, and prepend in Ruby?
- Advanced How does Rails handle database connection pooling?
- Advanced What is Rack and how does Rails relate to it?
- Advanced What is query optimization with explain in Rails?