ActiveRecord associations: polymorphic
Polymorphic associations let one ActiveRecord association point at several model types, decided per row. The course starts with a Comment that must attach to an Article or a Photo, and why one nullable column per type breaks down. It covers the commentable_type and commentable_id columns, the reverse side with has_many and as:, and dependent: :destroy. It also explains why a polymorphic column has no database foreign key and what a stale type raises. Finally, it shows Active Storage using the same mechanism and how to query by type.
What you'll learn
- ✓Why one nullable belongs_to column per type allows invalid rows
- ✓The commentable_type and commentable_id columns behind belongs_to with polymorphic: true
- ✓The reverse side with has_many and the as: option
- ✓How dependent: :destroy cascades per type and why no database foreign key applies
- ✓How a stale or bogus type raises NameError
- ✓How Active Storage attachments use the same mechanism, and querying by type
One association, several possible types
ActiveRecord associations: has_one/through covered belongs_to, has_many, has_one and :through, and each of them pointed at one other kind of model. Catalog::Lesson belongs_to :course always means a Catalog::Course on the other end. That fixed type is built into course_id: an integer column that…
Read the full lesson free →Curriculum
7 lessonsOne association, several possible types
Shows why one nullable belongs_to per type fails for a Comment attached to articles or photos.
The two columns a polymorphic belongs_to needs
Explains the commentable_type and commentable_id columns and how reading commentable returns the original row.
The reverse side: has_many ..., as: :commentable
Covers has_many with as: :commentable, which filters comments by type and id for each model.
dependent: :destroy, and a trap worth knowing
Shows dependent: :destroy cascading per type, the missing database foreign key, and NameError from stale types.
The same mechanism, already running in this app
Traces has_one_attached and has_many_attached to the polymorphic belongs_to inside ActiveStorage::Attachment.
Querying by type
Filters and counts records by their type column using ordinary where and group calls.
Putting it together: one association, resolved at runtime
Reviews the polymorphic pattern in two classes, from the type and id columns to querying.