No route matches [POST] for delete and update

℡╲_俬逩灬. 提交于 2020-01-03 02:04:52

问题


I know this question was asked a lot of times, but none of the recipes helped me so far.

I have an application written in Ruby 2.0.0, Rails 4.0.0 with following routes.rb:

resources :announcements do
end

Which generates the following routes:

        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

Then in HTML I use very simple construct:

<%= button_to 'X', announcement, method: :delete %>

Which produces the following code:

<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>

Everything looks pretty simple, clean and correct. Nevertheless I'm getting "No Route Matches" error. Why?


回答1:


The problem was in missing middleware. I have added

config.middleware.use Rack::MethodOverride

to /config/application.rb




回答2:


Try

<%= button_to "Delete", {:controller => :announcements, :action => 'destroy', :id => announcement.id }, :method => :delete %>



回答3:


That's because the routes for those paths need to have :method => :delete (delete path) & :method => :put (update path). POST won't work for either

As per the Rails Documentation:

In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database

You also need to use announcement_path for your URL helper



来源:https://stackoverflow.com/questions/19381685/no-route-matches-post-for-delete-and-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!