问题描述:

I was originally getting a routing error posted in Routing Errors on attempts to delete all records in a table using Rails 4 through a link_to, and that has been resolved.

Now I am having problems with "id=remove_all" being passed. I'm 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

ActiveRecord::RecordNotFound in AssessmentsController#destroy

Couldn't find Assessment with id=remove_all

# Use callbacks to share common setup or constraints between actions.

def set_assessment

@assessment = Assessment.find(params[:id])

end

The logs show:

Started DELETE "/assessments/remove_all" for 127.0.0.1 at 2014-01-31 15:41:41 -0500

Processing by AssessmentsController#destroy as HTML

Parameters: {"authenticity_token"=>"fooBarBaz=", "id"=>"remove_all"}

How do pass the collection of @assessments to the remove_all action using the Delete verb? Is this possible?

网友答案:

It is Because

resources :assessments

already have route to destroy like /assessment/:id with method :delete

so your remove_all_assessments_path will hit to that url bcoz it comes first in in your routes.rb file

To solve your problem u have to do something like this:-

resources :assessments, except: [:destroy] do
 collection do
   delete :remove_all
 end 
end

or define your remove_all_assessments url above it.

like

 match "/assessments/remove_all", to: "assessments#remove_all", via: [:delete], as: :remove_all_assessments
 resources :assessments do
 collection do
   delete :remove_all
 end 
end
相关阅读:
Top