#By adding a join table categories_posts in your database:
class CreateCategoriesPosts < ActiveRecord::Migration[6.0]
def change
create_table :categories_posts do |t|
t.references :post, foreign_key: true
t.references :category, foreign_key: true
t.timestamps
end
end
end
#And using through in your associations instructions in your models classes:
class Post < ActiveRecord::Base
has_many :categories_posts
has_many :categories, through: :categories_posts
end
class Category < ActiveRecord::Base
has_many :categories_posts
has_many :posts, through: :categories_posts
end
#And don’t forget to add the belongs_to in the new CategoriesPost model:
class CategoriesPost < ActiveRecord::Base
belongs_to :category
belongs_to :post
end