Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Last active June 8, 2021 00:38
Show Gist options
  • Save stevepolitodesign/74fc4eb8cbd5ebccf1c122e5a7adcdca to your computer and use it in GitHub Desktop.
Save stevepolitodesign/74fc4eb8cbd5ebccf1c122e5a7adcdca to your computer and use it in GitHub Desktop.
Polymorphic Table VS Join Table

has_many :through Association

A Post can have many Tags and a Tag can belong to many Posts. A has_many :through association may seem like a good approach, but what if a new model is introduced that also needs to have many Tags?

clas Post < ApplicationRecord
  has_many :post_tags
  has_many :tags, through: :post_tags
end
clas Tag < ApplicationRecord
  has_many :post_tags
  has_many :posts, through: :post_tags
end
clas PostTag < ApplicationRecord
  belongs_to :post
  belongs_to :tag
end

Polymorphic Association

Would a Polymorphic associations be more flexible? This would allow for additional models to be tagged later.

clas Post < ApplicationRecord
  has_many :tags, as: :taggable
end
clas Tag < ApplicationRecord
  belongs_to :taggable, polymorphic: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment