我知道很多次都会问这个问题,但到目前为止,没有一个食谱帮助过我。
我有一个用Ruby 2.0.0编写的应用程序,Rails 4.0.0以及以下routes.rb:
resources :announcements do
end
生成以下路线:
announcements GET /announcements(.:format) announcements#index
POST /announcements(.:format) announcements#create
new_announcement GET /announcements/new(.:format) announcements#new
edit_announcement GET /announcements/:id/edit(.:format) announcements#edit
announcement GET /announcements/:id(.:format) announcements#show
PATCH /announcements/:id(.:format) announcements#update
PUT /announcements/:id(.:format) announcements#update
DELETE /announcements/:id(.:format) announcements#destroy
然后在HTML中我使用非常简单的构造:
<%= button_to 'X', announcement, method: :delete %>
产生以下代码:
<form method="post" class="button_to" action="/announcements/525c0d28b9fd0171e2000003">
<div>
<input type="hidden" value="delete" name="_method">
<input type="submit" value="X">
<input type="hidden" value="DR+QjuAG9npqqWRV16Zq0G4Cq3lGpNHY0qjV8LJpUZo=" name="authenticity_token">
</div>
</form>
一切看起来都非常简单,干净和正确。不过我收到“No Route Matches”错误。为什么呢?
答案 0 :(得分:3)
问题在于缺少中间件。我添加了
config.middleware.use Rack::MethodOverride
到/config/application.rb
答案 1 :(得分:0)
尝试
<%= button_to "Delete", {:controller => :announcements, :action => 'destroy', :id => announcement.id }, :method => :delete %>
答案 2 :(得分:-1)
那是因为这些路径的路由需要:method => :delete
(删除路径)&amp; :method => :put
(更新路径)。 POST不适用于
在Rails中,资源丰富的路由提供HTTP谓词之间的映射 和控制器操作的URL。按照惯例,每个动作也会映射 到数据库中的特定CRUD操作
您还需要使用announcement_path
作为您的网址帮助