Implement polymorphic associations in Rails

BharteeTechRubyOnRails
2 min readJun 21, 2023

--

Definition:

Polymorphic associations in the context of database design and object-relational mapping (ORM) frameworks like Rails refer to a mechanism that allows a single database column to be associated with multiple different models or tables. It enables the creation of flexible and reusable relationships between database records.

In a polymorphic association, a database column is used to store both the type and the ID of the associated record. This allows a single column to be associated with multiple different tables and models. This type of association is useful when you have multiple models that can be associated with a common model, but each associated model may have a different table structure or behavior.

Step1:

Generate the necessary models and migration files using the Rails generator. In your case, you’ve already used the following commands to generate the models:

rails g model PolyComment content:text commentable:references{polymorphic}
rails g model Forum title
rails g model Event title
rails g model Post title

Step2:

Define the associations in the models. In your case, you’ve already defined the associations as follows:

class PolyComment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end

class Post < ApplicationRecord
has_many :poly_comments, as: :commentable
end

class Forum < ApplicationRecord
has_many :poly_comments, as: :commentable
end

class Event < ApplicationRecord
has_many :poly_comments, as: :commentable
end

Step3:

Now you can create instances of the models and associate them with comments. For example:

post = Post.create(title: "test")
comment = PolyComment.create(content: "test the comment", commentable: post)

In this example, a new Post an instance is created with the title "test." Then a PolyComment the instance is created with the content "test the comment" and associated with the post object.

Step4:

You can retrieve the associated comments for a specific model using the polymorphic association. For example, to retrieve the comments for a post:

post.poly_comments

Step5:

You can also access the associated object from a comment. For example, to retrieve the post associated with the comment:

p = PolyComment.last
PolyComment Load (0.3ms) SELECT "poly_comments".* FROM "poly_comments" ORDER BY "poly_comments"."id" DESC LIMIT ? [["LIMIT", 1]]
=>
#<PolyComment:0x00007fa700358e60
...
3.0.0 :009 > p.commentable
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=>
#<Post:0x0000559d185c6718
id: 1,
title: "test",
created_at: Wed, 21 Jun 2023 09:49:25.541943000 UTC +00:00,
updated_at: Wed, 21 Jun 2023 09:49:25.541943000 UTC +00:00>

--

--

BharteeTechRubyOnRails
BharteeTechRubyOnRails

Written by BharteeTechRubyOnRails

Ruby on Rails Developer || React Js || Rspec || Node Js

No responses yet