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!

Advertisements

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 )

Google photo

You are commenting using your Google 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