I have nested routes of categories/subcategories/products and my controller and view files are setup accordingly, but I now have some products that don't have subcategories. How, if possible, can I have some products part of a category, while others are part of a sub-category? I've seen many other posts on this, but none seem to address exactly what I'm looking to do.
current nested routes
resources :categories do
resources :subcategories do
resources :products
end
end
additional needed nested routes
resources :categories do
resources :products
end
My current Products controller Create method
def create
@category = Category.friendly.find(params[:category_id])
@subcategory = Subcategory.friendly.find(params[:subcategory_id])
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to category_subcategory_product_path(@category, @subcategory, @product), notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: category_subcategory_product_path(@category, @subcategory, @product) }
else
...
end
end
end
models
class Category < ApplicationRecord
has_many :subcategories
has_many :products, through: :subcategories
end
class Subcategory < ApplicationRecord
has_many :products
belongs_to :category
end
class Product < ApplicationRecord
belongs_to :subcategory
end