【发布时间】:2015-10-25 10:14:01
【问题描述】:
我一直在为这个问题摸不着头脑,但我一直收到这个错误
没有路线匹配 {:action=>"show", :category_id=>nil, :controller=>"products", :id=>nil} 缺少必需的键: [:category_id, :id]
在我的简单逻辑中,每当我选择 category_product_path 并传入类别时,我都应该拥有该类别中的产品列表。但我可能错过了一些东西。这是我的视图文件...我尝试了几个没有成功的东西
<% @products.each do |product| %>
<tr>
<td><%= link_to product.name, category_product_path(@category) %></td>
<td><%= product.category_id %></td>
<td><%= number_to_euro(product.price) %></td>
<td><%= product.stock %></td>
<td><%= image_tag(product.image.thumb) %></td>
<br>
</tr>
<% end %>
这是我的路线
namespace :admin do
resources :categories
resources :products
resources :orders
end
resources :categories, only: [:index, :show] do
resources :products, only: [:index, :show]
end
resources :orders, only: [:new, :create]
而我认为是控制器中某处的问题(而不是管理文件夹中的那些)
class CategoriesController < ApplicationController
before_action :set_category, only: [:show]
def index
@categories = Category.all
end
def show
@products = @category.products
end
private
def set_category
@category = Category.find(params[:id])
end
end
class ProductsController < ApplicationController
before_action :set_product, only:[:show]
def index
@products = Product.all
end
def show
end
private
def set_product
@product = Product.find(params[:id])
end
end
【问题讨论】:
-
category_products_path(category_id: @category)请注意,products是复数形式。 -
但是链接索引还是没有多大意义。我认为您正在寻找的是
link_to product.name, category_product_path(category_id: product.category, id: product) -
嘿。第一个不起作用,给出了同样的错误,但是第二个就像一个魅力。谢谢你。是的,这没有多大意义,我还在学习。我真正想做的是转到类别页面,然后从那里选择产品类别并列出它们。所以基本上这在某种意义上是索引......或者如果你愿意的话,它可能只是一个“过滤器”页面:)。哦,我有一个问题,你能向我解释一下这部分'category_id:product.category,id:product'吗?不清楚,我在rails文档中找不到关于具有多个参数的路径的任何内容
标签: ruby-on-rails ruby-on-rails-4