Routing Errors on attempts to delete all records i

2019-08-31 12:50发布

问题:

I am using Rails 4, and am trying to delete all the assessments using a link_to helper. The pertinent code is below:

routes.rb

   resources :assessments do
     collection do
       delete :remove_all
     end
   end

assessment index.html.erb

 <p>To delete all assessments in one swoop, click <%= link_to 'Remove ALL Assessments', remove_all_assessments_path, method: :destroy, data: { confirm: 'Are you sure?' } %>

assessments_controller.rb

  def remove_all
    @assessments = Assessment.all
    @assessments.each do |assessment|
        assessment.destroy(assessment.id)
     end
    flash[:notice] = "All assessments have been deleted."
    redirect_to assessments_url
  end

I run rake routes and

Prefix                 Verb   URI Pattern                       Controller#Action
remove_all_assessments DELETE /assessments/remove_all(.:format) assessments#remove_all

The HTML source generated for the link:

<p>To delete all assessments in one swoop, click <a data-confirm="Are you sure?" data-method="destroy" href="/assessments/remove_all" rel="nofollow">Remove ALL Assessments</a>

When I click on the 'Remove All Assessments' link, I expect to have the remove_all action run in the AssessmentsController, and delete all the assessments in @assessments, then redirect me to the assessments_url. However, when I click on the 'Remove ALL Assessments', link, I am brought to the url: http://localhost:3000/assessments/remove_all with the error No route matches [POST] "/assessments/remove_all"

What gives?

回答1:

It should be <p>To delete all assessments in one swoop, click <%= link_to 'Remove ALL Assessments', remove_all_assessments_path, method: :delete, data: { confirm: 'Are you sure?' } %>



回答2:

Verb is DELETE, so you should use the :delete method in your link_to.

There is no method DESTROY in the HTTP spec.