N:N relation for models
Sat Mar 20 2021 18:42:01 GMT+0000 (Coordinated Universal Time)
Saved by
@lisaxu
#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
content_copyCOPY
https://kitt.lewagon.com/camps/545/challenges?feature=flashcards&path=03-AR-Database%2F04-ActiveRecord-Advanced&feature=flashcards
Comments