I have created a join table for categories and products. Do I need a category_id column in my products database? When I go into my rails console and type Product.new there is no category attribute. If I would like to assign categories to a product how would I do this? This is my first time working with a join table and I am confused on how it works?
My tables:
create_table "categories", force: :cascade do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "category_id"
end
create_table "categories_products", id: false, force: :cascade do |t|
t.integer "category_id", null: false
t.integer "product_id", null: false
end
create_table "products", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "image_url"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image", default: "{}"
end
My associations:
class CategoryProduct < ActiveRecord::Base
belongs_to :category
belongs_to :product
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :categories
has_many :categories_products
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
has_many :categories_products
end
category portion of my products form:
<% for category in Category.all %>
<div>
<%= check_box_tag "product[category_ids][]", category.id, @product.categories.include?(category) %>
<%= category.name %>
</div>
<% end %>