0

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 %>
Kris
  • 187
  • 1
  • 2
  • 14

1 Answers1

0

You are already having the HABTM join table so you don't need to have category_id in products table.

you can assign categories to products like following in your rails console

product = Product.create(..)
category = Category.create(..)
product.categories << category //assigning category to product

exmaple explain here HABTM

Shani
  • 2,433
  • 2
  • 19
  • 23
  • Thank you very much for the response. The article helped me understand HABTM associations much better. – Kris May 12 '16 at 23:59