destroy 操作必须在 HTTP DELETE 请求上调用,而绝不能在 GET 上调用。您绝对应该从您的路线中修复以下代码:
resources products do ## missing : here, it should be :products
## member block not required
member do
get :destroy ## destroy should never be GET request
end
end
您只需将路线定义为:
resources :products ## Notice :products and not products
这将为您生成以下路线,您可以通过运行命令rake routes 进行检查
products GET /products(.:format) products#index
POST /products(.:format) products#create
new_product GET /products/new(.:format) products#new
edit_product GET /products/:id/edit(.:format) products#edit
product GET /products/:id(.:format) products#show
PATCH /products/:id(.:format) products#update
PUT /products/:id(.:format) products#update
DELETE /products/:id(.:format) products#destroy
注意最后生成的路由。
destroy 操作应该被称为 HTTP Delete 方法,这就是为什么在您的链接上您需要将 method: :delete 指定为
<% glyph_to "Delete", product, method: :delete, data: (confirm: "Are you sure that product" ##(product.id) is not used?") if can? (:destroy, product)%>
因此,当您单击此链接时,将发送一个 DELETE 请求,该请求将映射到您的 products#destroy 路由,即,
DELETE /products/:id(.:format) products#destroy
另外,您需要更新destroy 操作,如下所示:
def destroy
@product = Product.find(params[:id])
@product.destroy
redirect_to products_url ## products_url notice plural products
end
products_url 会将您重定向到products 的index 页面。
正如product_path 用于show,即显示特定产品。如果不向product_path 提供id,您也无法显示已删除的产品。因此,从逻辑上讲,您应该使用products_url 重定向到index 操作(注意使用**_url 进行重定向是可取的,但您也可以使用products_path)