Reputation: 3725
I get that if you have a posts and a categories table that the join table will be posts_categories. However you might have more than one type of category.
If we decide to create specialized category tables for each object type we would create a posts_categories table which would be a table of categories specifically for post objects. What would the many-to-many join table be called between posts and posts_categories?
Upvotes: 0
Views: 89
Reputation: 2624
If I were you, I would create the join table (categorizations
) with additional column(s):
rails g model Categorization post:references category:references new_column:new_type ....
### models/post.rb
class Post < ApplicationRecord
has_many :categorizations
has_many :categories, through: :categorizations
end
## models/categorization
class Categorization < ApplicationRecord
belongs_to :post
belongs_to :category
## You can add new columns as many as you want, just like other tables
end
# models/category.rb
class Category < ApplicationRecord
has_many :categorizations
has_many :posts, through: :categorizations
end
Upvotes: 1
Reputation: 509
I'm not sure I can fully understand your question. But, if you want create a many-to-many relationship between Post and Category, you can try as bellow:
# post.rb
class Post < ApplicationRecord
has_many :post_categories
has_many :categories, through: :post_categories
end
and
#post_category.rb
class PostCategory < ApplicationRecord
belongs_to :post
belongs_to :category
end
and
# category.rb
class Category < ApplicationRecord
has_many :post_categories
has_many :posts, through: :post_categories
end
Hope it helps.
Upvotes: 0