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
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