0
0
Ruby on Railsframework~5 mins

Polymorphic associations in Ruby on Rails

Choose your learning style9 modes available
Introduction

Polymorphic associations let one model belong to more than one other model using a single association. This helps keep your code simple and flexible.

When you want to attach comments to different models like posts and photos.
When you want to add tags that can belong to articles, events, or users.
When you want to track likes on various content types such as videos and blog posts.
Syntax
Ruby on Rails
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

The model with belongs_to uses polymorphic: true.

The other models use has_many with as: :association_name.

Examples
Tags can belong to either pictures or articles using polymorphic association.
Ruby on Rails
class Picture < ApplicationRecord
  has_many :tags, as: :taggable
end

class Article < ApplicationRecord
  has_many :tags, as: :taggable
end

class Tag < ApplicationRecord
  belongs_to :taggable, polymorphic: true
end
Likes can be added to videos or blog posts with one Like model.
Ruby on Rails
class Like < ApplicationRecord
  belongs_to :likeable, polymorphic: true
end

class Video < ApplicationRecord
  has_many :likes, as: :likeable
end

class BlogPost < ApplicationRecord
  has_many :likes, as: :likeable
end
Sample Program

This example shows how comments can belong to either a post or a photo. We create a post and a photo, then add comments to each. Finally, we print the comment bodies.

Ruby on Rails
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

# Usage example in Rails console:
post = Post.create(title: "My Post")
photo = Photo.create(title: "My Photo")

comment1 = Comment.create(body: "Great post!", commentable: post)
comment2 = Comment.create(body: "Nice photo!", commentable: photo)

puts post.comments.first.body
puts photo.comments.first.body
OutputSuccess
Important Notes

Remember to add commentable_type and commentable_id columns in the comments table.

Polymorphic associations simplify your database by using one table for multiple relationships.

Summary

Polymorphic associations let one model belong to many others using one interface.

Use belongs_to :name, polymorphic: true and has_many :name, as: :name.

This keeps your code DRY and flexible for different related models.