DEV Community

Cover image for Polymorphic associations in Rails
Oliver
Oliver

Posted on • Originally published at codeandclay.com

3

Polymorphic associations in Rails

A model can associate with other models by way of a polymorphic association. This can be useful when the associated models are not of the same class but share a common interface, or when a model shares the same type of relationship with multiple other models.

For example, three models Post, Project, and Issue may have many comments.

Instead of creating a different comment model for each of these three models (PostComment, ProjectComment…) it would be much more straightforward to have a single Comment model and establish a relationship to a subject.

create_table :comments do |t|
  t.text :body
  t.references :subject, polymorhic: true
Enter fullscreen mode Exit fullscreen mode

The subject could be a Post, Project, Issue or any other model we wish to attach a comment to.

The polymorphic option, instructs the database to store the associated object's type. The above migration creates a :subject_type column.

The relationships are established in the models like so:

class Comment < ApplicationRecord
  belongs_to :subject, polymorphic: true
end

class Post < ApplicationRecord
  has_many :comments, as: subject
end

class Project < ApplicationRecord
  has_many :comments, as: subject
end

class Issue < ApplicationRecord
  has_many :comments, as: subject
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay