我收到此行的NoMethodError<%= link_to“删除”,delete_product_path(p),:confirm => “你确定吗?”,:method => :删除%>或<%= link_to“删除”,delete_product_path(p),:confirm => “你确定吗?”,:method => :删除%> ..我使用了我的路线资源..
问题:为什么?
注意:我也试过<%= link_to'删除',delete_product_path(p)就像视频说的那样,它不适用于我
查看
<html>
<head>
<title>MY STORE!</title>
</head>
<body>
<h1><align="center"> WELCOME TO MY STORE</h1>
<%= link_to 'Add Product', new_product_path %>
<table border = "1" width="100%">
<tr>
<td>ID</td>
<td>Name</td>
<td>Image</td>
<td>Size</td>
<td>Price</td>
<td>Created At</td>
<td>Updated At</td>
<td>Action</td>
</tr>
<% @product.each do |p| %>
<tr>
<td><%= p.id %></td>
<td><%= p.name %></td>
<td><%= p.size %></td>
<td><%= p.price %></td>
<td><%= p.created_at.strftime("%B, %d, %Y") %></td>
<td><%= p.updated_at.strftime("%B, %d, %Y") %></td>
<td>
<%= link_to 'View', product_path(p) %>
<%= link_to 'Edit', edit_product_path(p) %>
<%= link_to 'Delete', delete_product_path(p), :confirm => "Are you sure?", :method => :delete %>
</td>
</tr>
<% end %>
</table>
</body>
</html>
路线
Rails.application.routes.draw do
resources :products
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
控制器
class ProductsController < ApplicationController
def index
@product = Product.all.order('created_at DESC')
end
def show
@post = Product.find(params[:id])
end
def new
@product = Product.new
end
def create
@post = Product.new(post_params)
if @post.save
redirect_to (products_path)
else
redirect_to (new_product_path)
end
end
def edit
@product = Product.find(params[:id])
end
def update
@product = Product.find(params[:id])
if @product.update_attributes(post_params)
redirect_to (products_path)
else
redirect_to (products_path)
end
end
def delete
@product = Product.find(params[:id])
end
def destroy
@product = Product.find(params[:id])
@product.destroy
redirect_to(products_path)
端 私人的 def post_params params.require(:product).permit(:name,:size,:price) 端
end
答案 0 :(得分:1)
你想要的是
<%= link_to 'Delete', p, method: :delete, data: { confirm: 'Are you sure?' } %>
路线是
/products/:id
因此命名路径不是delete_product_path。它是具有id的产品路径,并且使用方法delete来销毁它。
从控制器中删除delete方法并像这样设置destroy方法
# DELETE /products/1
# DELETE /products/1.json
def destroy
@product = Product.find(params[:id])
@product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
它寻找的方法是破坏。你永远不会打电话给#34; .destroy&#34;这是实际删除记录的动作。你的方法所做的是根据id找到它,这就是它显示的原因。