[Rails] has_many :through
Hi
I have a problem with has_many :trough association. I have 2 tables, Product and Category, and when I create new Product, I should make checkboxes to choose in what categories the product . I've made model category_product where I store the association from the Category and Product tables. Here is some of the code.
class Category < ActiveRecord::Base
has_many :category_products, dependent: :destroy
has_many :products, :through => :category_products
accepts_nested_attributes_for :category_products
class CategoryProduct < ActiveRecord::Base
belongs_to :category
belongs_to :product
accepts_nested_attributes_for :category
class Product < ActiveRecord::Base
has_many :category_products, dependent: :destroy
has_many :categories, :through => :category_products
accepts_nested_attributes_for :category_products
class ProductsController < ApplicationController
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
if @product.save
items_array = category_params
items_array.each do |key, value|
if value != ""
@category_product = CategoryProduct.new(:category => value, :product => @product.id)
@category_product.save
end
#category_products.create!(:category => arrayitem.id, :product => @product.id)
end
#@categories = Category.find(category_params)
# @categories.each do |category|
#category_products.create!(:category => category.id, :product => @product.id)
I have a problem with has_many :trough association. I have 2 tables, Product and Category, and when I create new Product, I should make checkboxes to choose in what categories the product . I've made model category_product where I store the association from the Category and Product tables. Here is some of the code.
class Category < ActiveRecord::Base
has_many :category_products, dependent: :destroy
has_many :products, :through => :category_products
accepts_nested_attributes_for :category_products
class CategoryProduct < ActiveRecord::Base
belongs_to :category
belongs_to :product
accepts_nested_attributes_for :category
class Product < ActiveRecord::Base
has_many :category_products, dependent: :destroy
has_many :categories, :through => :category_products
accepts_nested_attributes_for :category_products
class ProductsController < ApplicationController
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
if @product.save
items_array = category_params
items_array.each do |key, value|
if value != ""
@category_product = CategoryProduct.new(:category => value, :product => @product.id)
@category_product.save
end
#category_products.create!(:category => arrayitem.id, :product => @product.id)
end
#@categories = Category.find(category_params)
# @categories.each do |category|
#category_products.create!(:category => category.id, :product => @product.id)
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home