2012-09-20 87 views
0

每當我遇到同樣的情況時,我都有一個困擾我的問題。創建嵌套資源

如何創建一個嵌套的資源..

我有以下回購

https://github.com/abhishekdagarit/app-e-commerce.git 

您可以克隆回購並創建dabtabase看到該項目。

我需要類別添加到產品..

product 
    belongs_to_and_has_many :categories 

category 
    has_many :products 

誰能告訴我如何實現這一目標的正常工作...... 我添加了註釋,個別產品,但我花了四小時做到這一點...

這就是我通常做...

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 

現在的事情是,這些步驟只是似乎沒有工作...

我需要有人來幫助我的幾行代碼的工作,以創建一個嵌套的資源...

回答

1

你可以找到從軌道引導Nested Resources

你試過下面的嵌套資源嗎?

resources :categories do 
    resources :products 
end