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

独自空忆成欢 提交于 2019-12-24 07:35:28

问题


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:


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"


来源:https://stackoverflow.com/questions/56825149/curl-command-to-delete-from-rails-api-based-on-where-predicate

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