Ruby on Rails Polymorphic Associations Explained
By Ankur Chauhan
Sometimes a single model needs to connect with multiple other models — not just one specific type. That’s where polymorphic associations come in.
How It Works
Polymorphic associations use two database columns:
- One storing the related model’s ID
- Another capturing that model’s type (class name)
This allows a single association to point to different model types dynamically.
Real-World Applications
- E-commerce — products to attachments (images, videos, documents)
- Inventory Management — shipments to different item types
- CMS — files attached to different content types (articles, pages, comments)
Implementation
class Attachment < ApplicationRecord
belongs_to :attachable, polymorphic: true
end
class Product < ApplicationRecord
has_many :attachments, as: :attachable
end
class Article < ApplicationRecord
has_many :attachments, as: :attachable
end
The migration creates the polymorphic columns:
create_table :attachments do |t|
t.references :attachable, polymorphic: true
t.timestamps
end
When to Use Polymorphic Associations
Use them when you have a model that logically belongs to multiple different parent types. Common examples include comments, attachments, tags, and activity logs.
Conclusion
Polymorphic associations are a powerful Rails feature that reduces code duplication and keeps your data model clean. Use them when a single model needs to relate to multiple other models in the same way.