Curl command to DELETE from rails API based on where predicate?

Viewed 460

I can see from here how to delete a table record by id

i.e. this deletes the user record with id = 1

curl -X DELETE "http://localhost:3000/users/1"

But what if I wanted to delete records based on something else, e.g. all users with name: "John", how would that be done via a curl command?

Update: I thought curl -X DELETE -d "name=John" "http://localhost:3000/users" may work, but it doesn't

1 Answers

In that scenario, the API would change a bit. The route for the default DELETE API on Rails requires an ID to be passed as input compulsorily. The request format is some_api/:id. However, for your use case, you would need a different API which does not compulsorily require an ID as input. It could be a multipurpose API which deletes by name, id etc. For example:

# app/controllers/users_controller.rb
def custom_destroy
  @users = User.filtered(filter_params)
  @users.destroy_all
  <render your response>
end

def filter_params
  params.permit(:id, :name, <Any other parameters required>)
end

# app/models/user.rb
scope :filtered, -> (options={}) {
  query = all
  query = query.where(name: options[:name]) if options[:name].present?
  query = query.where(id: options[:id]) if options[:id].present?
  query
}

The route of this could be described as:

resources :users do
  collection do
    delete :custom_destroy
  end
end

This would result in the route: localhost:3000/users/custom_destroy which can be called with the DELETE action. i.e.

curl -X DELETE "http://localhost:3000/users/custom_destroy?name=John"
Related