从Rails API的卷曲命令基于谓词从DELETE删除? [英] Curl command to DELETE from rails API based on where predicate?
问题描述
我可以从
I can see from here how to delete a table record by id
即这会删除ID = 1的用户记录
i.e. this deletes the user record with id = 1
curl -X DELETE "http://localhost:3000/users/1"
但是,如果我想基于其他内容删除记录,例如所有具有 name:"John"
的用户,如何通过curl命令完成该操作?
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?
更新:我认为 curl -X DELETE -d"name = John""http://localhost:3000/users"
可能有效,但是不起作用
Update: I thought curl -X DELETE -d "name=John" "http://localhost:3000/users"
may work, but it doesn't
推荐答案
在这种情况下,API会有所变化.在Rails上使用默认 DELETE
API的路由要求将ID作为输入强制传递.请求格式为 some_api/:id
.但是,对于您的用例,您将需要一个不同的API,该API不需要强制将ID作为输入.它可能是一个多用途的API,可以按名称,ID等删除.例如:
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
}
其路线可描述为:
resources :users do
collection do
delete :custom_destroy
end
end
这将导致路由: localhost:3000/users/custom_destroy
,可以使用 DELETE
操作调用该路由.即
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"
这篇关于从Rails API的卷曲命令基于谓词从DELETE删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!