Polymorphic through

Classic polymorphism:

http://www.sihui.io/has_many-through-and-polymorphic/

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
end

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

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

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

Seeding:

comment = user.comments.new
comment.commentable = comment
comment.save!

Leave a comment