Reputation: 45
I'm currently creating the database schema for a new Rails project and I want to things right, so I better ask!
Imagine this: I have a table called "articles" and these articles should have tags. The thing I would do now is relatively simple. Create another table called "tags" and a third one called "article_tags". Every article and tag has a unique id and "article_tags" is the mapping table which brings the right article ids and tag ids together.
Tables:
- articles
- tags
- article_tags (mapping)
The "problem" I currently have is this: Not only articles have tags but also my "users" (another table). These tags have to be in two different tables which would then result in some pretty odd naming.
Tables:
- articles
- article_tags (no mapping)
- article_article_tags (mapping???)
- users
- user_tags (no mapping)
- user_user_tags (mapping???)
Do you have any (general) tips how to improve the naming of these tables because what you can see above doesn't make me very happy...
Upvotes: 0
Views: 158
Reputation: 8604
I think you can use polymorphic association to do it, something like this:
class User
has_many :taggings, as: :taggable
has_many :tags, through: :taggings
end
class Article
has_many :taggings, as: :taggable
has_many :tags, through: :taggings
end
class Tagging
belongs_to :taggable, polymorphic: true
belongs_to :tag
end
class Tag
end
So you just need 4 tables: users, articles, taggings, tags.
Upvotes: 1