Reputation: 77
I have a question that bothers me every time I face the same situation.
How to create a nested resource..
I have the following repo
https://github.com/abhishekdagarit/app-e-commerce.git
You can clone the repo and create the dabtabase to see the project.
I need to add categories to the products..
product
belongs_to_and_has_many :categories
category
has_many :products
Could anyone please tell me how to achieve this to work properly... I added comments to individual products but that took me four hours to achieve that...
This is what I normally do...
1). add the category model using
rails g model category category_type:string
2). then add the has_to and the belongs_to_and_has_many in the models
3). add the controller
rails g controller categories
4). add the following lines in the categories controller
class CategoriesController < ApplicationController
def new
@product = Product.find(params[:product_id])
@category = @product.categories.build
respond_with(@category)
end
def create
@product = Product.find(params[:product_id])
@category = @product.categories.create(params[:category])
redirect_to product_path(@product)
end
end
Now the thing is that these steps just don't seem to work...
I need someone to help me with the few lines to code that work in order to create a nested resource...
Upvotes: 0
Views: 169
Reputation: 3717
You might also want to checkout:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
Upvotes: 0
Reputation: 4476
You can find the Nested Resources from rails guides.
did you try the following nested resources?
resources :categories do
resources :products
end
Upvotes: 1