没有身份证,找不到Menucard。嵌套资源

时间:2012-11-28 10:29:49

标签: ruby-on-rails resources nested

当我想进入我的Menucards产品索引(http:// localhost:3000 / menucards / 1 / products)时,我收到以下错误: 没有身份证,找不到Menucard。 在这个页面中,我想显示当前菜单卡中的所有产品。

这是我的产品控制器:

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>

1 个答案:

答案 0 :(得分:0)

请参阅“load_menucard”定义中的问题。因为它是嵌套资源,所以它应该是params [:menucard_id]而不是params [:id]。

替换

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

通过

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

希望它有效!