Polymorphic through

Classic polymorphism:


Edge case polymorphism:

If somehow the requirement is to turn the existing table into a polymorphic table and any newly added table would be associated with it, it could be done like:

Existing tables: User, Comment
User has many Comments

Create a new table BookComment which shares most of the attributes with Comment.
Instead of using a single inheritance approach, this could be done with polymorphism association

class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true

class BookComment < ApplicationRecord
has_one :comment, as: :commentable, dependent: :nullify

class User < ApplicationRecord
has_many :book_comments, through: :comments, source: :commentable, source_type: 'BookComment'

Then join query can be made to query user's book_comments joining comment:
user.book_comments.joins(:comment).where("comments.status =? ", :foo)


comment = user.comments.new
comment.commentable = comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s