Rails Polymorphic Associations

Photo by Julian Hochgesang on Unsplash
class Comment < ApplicationRecord
# uses a `commentable_type` column and a
# `commentable_id` column which can be filled by any of the below
# models’ class name and id
belongs_to :commentable, polymorphic: true
end
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
class Item < ApplicationRecord
has_many :comments, as: :commentable
end
class Image < ApplicationRecord
has_many :comments, as: :commentable
end
comment.commentable # will return whichever record (the Post Item or Image that comment belongs to)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store