我可以从here看到如何通过id删除表记录
即这将删除 id = 1 的用户记录
curl -X DELETE "http://localhost:3000/users/1"
但是如果我想根据其他内容删除记录怎么办?所有name:“John”
的用户,如何通过curl命令完成?
更新:我认为curl -X DELETE -d "name=John""http://localhost:3000/users"
可能有效,但事实并非如此
最佳答案
在这种情况下,API 会发生一些变化。 Rails 上默认 DELETE
API 的路由要求强制传递 ID 作为输入。请求格式为some_api/:id
。但是,对于您的用例,您将需要一个不同的 API,该 API 不强制要求 ID 作为输入。它可以是一个多用途 API,可以按名称、ID 等进行删除。例如:
# 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
操作调用该路由。即
curl -X DELETE "http://localhost:3000/users/custom_destroy?name=John"
关于ruby-on-rails - 基于 where 谓词从 Rails API 中删除的 Curl 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56825149/