2012-11-28 9 views
1

當我想進入我的Menucards產品索引(http:// localhost:3000/menucards/1/products)時,出現以下錯誤: 找不到沒有ID的Menucard。 在此頁面中,我想顯示當前菜單卡中的所有產品。找不到身份證的Menucard。嵌套資源

這是我的ProductsController:

class ProductsController < ApplicationController 
before_filter :load_menucard 

layout 'admin' 

def index 
    @products = @menucard.product.all 
end 

def new 
    @menucard = Menucard.find(params[:id]) 
    @product = @menucard.product.new 
    redirect_to @product 
end 

def create 
    @menucard = Menucard.find(params[:id]) 
    @product = @menucard.product.new(params[:product]) 
    if @product.save 
     redirect_to(:action => 'index') 
    else 
     render 'new' 
    end 
end 

def edit 
    @product = Product.find(params[:id]) 
end 

def destroy 
    @product = Product.find(params[:id]) 
    delete_product 
end 

def update 
    @product = Product.find(params[:id]) 
    if @product.update_attributes(params[:product]) 
     #redirect_to @product 
     redirect_to(:action => 'index') 
    else 
     render 'edit' 
    end 
end 

private 

def load_menucard 
    @menucard = Menucard.find(params[:id]) 
end 

end 

menucardscontroller:

class MenucardsController < ApplicationController 

layout 'admin' 

def new 
    @menucard = Menucard.new 
end 

def update 
    @menucard = Menucard.find(params[:id]) 
    if @menucard.update_attributes(params[:menucard]) 
     #redirect_to @menucard 
     redirect_to(:action => 'index') 
    else 
     render 'edit' 
    end 
end 

def edit 
    @menucard = Menucard.find(params[:id]) 
end 

def index 
    @menucards = Menucard.all 
end 

def create 
    @menucard = Menucard.new(params[:menucard]) 
    if @menucard.save 
     #redirect_to @menucard 
     redirect_to(:action => 'index') 
    else 
     render 'new' 
    end 
end 

def destroy 
    @menucard = Menucard.find(params[:id]) 
    if menucard.destroy 
     redirect_to(:action => 'index') 
    end 
end 
end 

產品視圖索引:

<h1>Alle producten</h1> 
<%= link_to("Product toevoegen", {:action => 'new' }, :class => 'btn btn-green') %> 
<table> 
<thead> 
    <tr> 
     <th scope="col">Naam</th> 
     <th scope="col">Beschrijving</th> 
     <th scope="col">Prijs</th> 
    </tr> 
</thead> 
<tbody> 
<% @products.each do |p| %> 
     <tr> 
      <td><a href="#" title=""><%= p.name %><%= link_to("- bewerken", { :action => 'edit', :id => p.id}, :class => 'show-edit') %></a></td> 
      <td><%= p.discription %></td> 
      <td><%= p.price %></td> 
     </tr> 
    <% end %> 
</tbody> 
</table> 

回答

0

看到的問題是在你的 'load_menucard' 的定義。由於它是嵌套資源,它應該是params [:menucard_id]而不是params [:id]。

更換

@menucard = Menucard.find(params[:id]) 

通過

@menucard = Menucard.find(params[:menucard_id]) 

希望工程!

+0

Thnx的答覆。將其更改爲menucard_id後,我得到以下錯誤:未定義的方法'產品'爲#

+0

我發現了什麼導致了我的下一個錯誤。在'索引'的定義中,我使用'@ menucard.product.all'產品需要是複數。 Thnx爲您提供幫助! –