我有一个名为NoteCategory的模型,它充当Notes和Categories之间的连接表。
到目前为止,我已经使用脚手架来完成RoR中的所有操作。我正在努力学习如何更多地手动做一些事情。
我想在一个便笺上的每个类别旁边显示一个链接,该链接将从便笺中删除该类别。所以我需要创建一个路由来删除连接表中的条目。
到目前为止,我已经创建了一个控制器
class NoteCategoriesController < ApplicationController
def destroy
notecategory = NoteCategory.find(params[:id])
notecategory.destroy
respond_to do |format|
format.html { redirect_to(notes_url) }
format.xml { head :ok }
end
end
end
然后我将此行添加到routes.db
map.resources :note_categories
以下是视图中的链接:
<%= button_to 'Delete', :confirm => 'Are you sure?', :controller => "notecategories",:action => :destroy %>
当我点击按钮时,收到以下错误消息:
No route matches "/notecategories/destroy" with {:method=>:post}
我做错了什么?谢谢你的阅读。
答案 0 :(得分:1)
map.resources
不会创建/$controller/destroy
路由。运行rake routes
并查看具体内容。
至于说得对,这个'删除'按钮是由简单的CRUD应用程序的scaffold命令生成的,所以它应该可以工作。
<%= link_to 'Destroy', event, :confirm => 'Are you sure?', :method => :delete %>
修改强>
整个'index.html.erb'页面由'scaffold'命令生成。它应该给你一般的想法。
<h1>Listing events</h1>
<table>
<tr>
<th>Name</th>
<th>Budget</th>
</tr>
<% @events.each do |event| %>
<tr>
<td><%=h event.name %></td>
<td><%=h event.budget %></td>
<td><%= link_to 'Show', event %></td>
<td><%= link_to 'Edit', edit_event_path(event) %></td>
<td><%= link_to 'Destroy', event, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New event', new_event_path %>
答案 1 :(得分:0)
尝试:
<%= button_to 'Delete', :confirm => 'Are you sure?', :controller => "notecategories",:action => :destroy, :method => :delete %>
注意:方法
这是因为RESTful路由使用那些PUT,DELETE,POST等动作词汇在一起的路径(即。/ notecategories / destroy with:delete一起用于销毁记录)