我有两个表类别,产品。产品具有外键类别。我正在尝试通过具有以下代码的产品通过index.html.erb删除(在视图中):
<td><%= link_to 'Destroy', category_product_path(product), method: :delete, data: { confirm: 'Are you sure?' } %></td>
但是,所有这些操作都会留下以下错误:
No route matches [DELETE] "/categories/product/products"
首先,为什么我会收到此错误,在路线或耙路中的任何地方都没有'/ categories / product / products'网址?下面是rake route命令(省略了设计路线):
category_products GET /categories/:category_id/products(.:format) products#index
POST /categories/:category_id/products(.:format) products#create
new_category_product GET /categories/:category_id/products/new(.:format) products#new
edit_category_product GET /categories/:category_id/products/:id/edit(.:format) products#edit
category_product GET /categories/:category_id/products/:id(.:format) products#show
PATCH /categories/:category_id/products/:id(.:format) products#update
PUT /categories/:category_id/products/:id(.:format) products#update
DELETE /categories/:category_id/products/:id(.:format) products#destroy
categories GET /categories(.:format) categories#index
POST /categories(.:format) categories#create
new_category GET /categories/new(.:format) categories#new
edit_category GET /categories/:id/edit(.:format) categories#edit
category GET /categories/:id(.:format) categories#show
PATCH /categories/:id(.:format) categories#update
PUT /categories/:id(.:format) categories#update
DELETE /categories/:id(.:format) categories#destroy
categories_new GET /categories/new(.:format) categories#new
POST /categories/:id(.:format) categories#create
GET /categories(.:format) categories#index
DELETE /categories/:id(.:format) categories#destroy
GET /categories/:id/products/new(.:format) products#new
POST /categories/:id/products/:id(.:format) products#create
GET /categories/:id/products(.:format) products#index
DELETE /categories/:id/products/:id(.:format) products#destroy
编辑:这是通过放置:
解决的resources :categories do
resources :products, shallow: true
end
routes.rb中的“删除”链接中仅允许“产品” ...
答案 0 :(得分:0)
由于它是嵌套路线,因此您需要在路线中传递类别ID。喜欢:
<%= link_to 'Destroy', category_product_path(product, category_id: category.id), method: :delete, data: { confirm: 'Are you sure?' } %>
此处,在路线category_product_path(product, category_id: category.id)
中,类别是产品所属的类别。
您还可以使用category_product_path(product, category_id: product.category.id)
作为删除路线。
答案 1 :(得分:0)
使用
resources :categories do
resources :products, shallow: true
我能够只使用“产品”作为网址/路径