2017-07-22 40 views
0

我正在研究小型Rails应用程序的销毁功能。目前,当我点击删除我收到以下错误:为什么销毁方法不正确地重定向?

No route matches [POST] "/note/1" 

下面是相关控制方法:

def destroy 
    if Note.find(params[:id]).destroy 
    redirect_to note_index_path, notice: 'Note deleted!' 
    else 
    redirect_to note_path, notice: 'Note failed to updated' 
    end 
end 

这里是一个链接例如:

<p><%= link_to 'Delete Note', { action: :destroy, id: @note.id }, method: :destroy, data: { confirm: 'Are you sure?' } %></p> 

这里是路线:

Prefix Verb URI Pattern    Controller#Action 
note_index GET /note(.:format)   note#index 
      POST /note(.:format)   note#create 
    new_note GET /note/new(.:format)  note#new 
edit_note GET /note/:id/edit(.:format) note#edit 
     note GET /note/:id(.:format)  note#show 
      PATCH /note/:id(.:format)  note#update 
      PUT /note/:id(.:format)  note#update 
      DELETE /note/:id(.:format)  note#destroy 
     root GET /      note#index 
+0

准确地说,为什么它说 - 没有该路线的POST请求。 –

回答

2

你并不需要指定actionlink_to帮手,当你犯了一个DESTROY要求,尽量只路过的资源,并指定methoddelete

<p><%= link_to 'Delete Note', @note, method: :delete, data: { confirm: 'Are you sure?' } %></p> 

@note对象会给你id,也无需指定它。

如果你让你的路线等待一个PARAM id/note/:id,那么Rails会采取第二个参数传递的对象的id值在link_to在这种情况下。

+0

由于在我的控制器中调用该方法,方法会被破坏吗?我试图按照CRUD模型。另外,我必须在我的项目中配置jquery才能使弹出窗口工作,但我甚至不确定这是否使用jQuery的哪一部分。 – pareod375

+0

使方法删除工作,但我不明白什么都改变。你是说'@ note'相当于'{action::destroy,id:@ note.id}'?此外,是jquery部分的方法::删除,数据:{确认:'你确定吗?' }'?它如何知道使用我的销毁方法? – pareod375

+0

如果您将方法指定为delete,则不需要使用action:destroy,这会为您生成的anchor标记添加一个data-method = delete属性,这样它就不是GET请求,但DELETE指向生成的url,可能类似于'/ notes/1'('notes /:id'),这样它只保留'id:@ note.id',可以简化为'@ note' 。 –