Performance: Polymorphic associations
Polymorphic associations affect database query speed and server response time, impacting how fast pages load data.
class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end # In controller @comments = Comment.includes(:commentable).all @comments.each do |comment| puts comment.commentable.title end
class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end # In controller @comments = Comment.all @comments.each do |comment| puts comment.commentable.title end
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| N+1 queries on polymorphic associations | Minimal DOM nodes | 0 reflows | Low paint cost | [X] Bad |
| Eager loading polymorphic associations | Minimal DOM nodes | 0 reflows | Low paint cost | [OK] Good |
belongs_to :name, polymorphic: true in the model that belongs to multiple types.class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end class Post < ApplicationRecord has_many :comments, as: :commentable end class Photo < ApplicationRecord has_many :comments, as: :commentable end
post.comments.first.commentable_type return if the first comment belongs to a Post?commentable_type.commentable_type will be "Post".class Picture < ApplicationRecord belongs_to :imageable, polymorphic: true end
imageable_type and imageable_id to be present for a valid association.imageable_type: nil, which breaks the association and causes an error.commentable interface, allowing multiple models to share comments.belongs_to :commentable, polymorphic: true in Comment and has_many :comments, as: :commentable in Article and Event.Pass the test and this pattern moves unknown