0

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...

2 Answers 2

1

You can find the Nested Resources from rails guides.

did you try the following nested resources?

resources :categories do
    resources :products
end
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.