'RESTful route for deleting all records in Rails
I have seen this question, but the only answer there suggests creating a custom route, which I am reluctant to do. What are the alternatives, using Rails' default RESTful routes?
In particular, I've begun using this setup:
# routes.rb
# Note the singular resource
resource :all_apples, path: 'apples/all', only: :destroy
# all_apples_controller.rb
class AllApplesController
def destroy
# Something like:
User.find(params[:id]).apples.delete_all
end
end
Then I can do DELETE /apples/all to delete all apple records.
I would also have a separate ApplesController with the standard individual CRUD actions, so I can still do, for example, GET /apples.
Would this be a "RESTful" way to solve the problem? Are there any notable issues with it?
Note
My actual use case has to do with token revocation. I want an endpoint that revokes all of a user's web tokens. I'm currently using DELETE /users/:id/tokens/all, as described above.
Solution 1:[1]
I have been thinking about this. I really don't like to do anything like this on a controller.
- I would create a special nested route for users
# config/routes.rb
resources :users do
delete '/delete_all_apples', to: 'users#delete_all_apples'
end
So now we have a special route to delete all apples from users
on the console you can find this routes like this
rails routes | grep delete_all_apples
# user_delete_all_apples DELETE /users/:user_id/delete_all_apples(.:format) users#delete_all_apples
- On your view your link should be
<%= link_to 'Destroy All Apples', user_delete_all_apples_path(user.id), data: {:confirm => 'Are you sure?'}, :method => :delete %>
- Your Controller
class UsersController < ApplicationController
def delete_all_apples
User.find(params[:id]).delete_all_apples
end
end
- On your Model
class User < ActiveRecord::Base
has_many :apples
def delete_all_apples
apples.delete_all
end
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
