Junior Track Roadmap

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
Free preview · Lesson 1 3 min read

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 lessons
Type to start searching...