ruby-on-rails - 基于 where 谓词从 Rails API 中删除的 Curl 命令?

标签 ruby-on-rails curl ruby-on-rails-5

我可以从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/

相关文章:

ruby-on-rails - 比较 rspec 自定义 ActiveRecord::RecordInvalid 错误消息

ruby-on-rails - 尝试在 Controller 中加载服务时发生 Rails 错误

ruby-on-rails-5 - 使用 ActionCable,有没有办法计算 channel 内有多少订阅者?

mysql - rails 5.1 : Primary Key is not a BIGINT

ruby-on-rails - ruby 中的意外表达式评估

ruby-on-rails - 将 Rails 迁移标记为已迁移

ruby-on-rails - 错误率: attr_encrypted assignment doesn't get written?

linux - bash | curl | curl 2 个 URL 然后停止

apache - 为什么 apache 接受这个无效的范围请求?

http - 我可以让 curl 只打印响应代码吗?