【问题标题】:Curl command to DELETE from rails API based on where predicate?基于where谓词从rails API中删除的Curl命令?
【发布时间】:2019-06-30 13:20:19
【问题描述】:

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" 可能有效,但它没有

【问题讨论】:

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


    【解决方案1】:

    在这种情况下,API 会发生一些变化。 Rails 上默认的DELETE API 的路由要求将 ID 作为输入强制传递。请求格式为some_api/:id。但是,对于您的用例,您将需要一个不同的 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"
    

    【讨论】:

    • 要添加到这个答案中,curl 请求会是什么样子? curl -X DELETE "http://localhost:3000/name=John"
    • @Anuj 我试过curl -X DELETE "http://localhost:3000/users/custom_destroy&amp;name=John"curl -X DELETE -d "name=John" "http://localhost:3000/users/custom_destroy"。两者都返回{"status":404,"error":"Not Found","exception":"#\u003cActiveRecord::RecordNotFound: Couldn't find User with 'id'=custom_destroy\u0026name=John\u003e"
    • 另外,def filter_params 等是否进入控制器的“私有”部分?
    • 我一直在摆弄,但还是没有运气。有什么想法吗?
    • filter_params 将进入私人部分。我会在我的本地机器上尝试一些东西然后回来?奇怪的是你得到一个404。你添加路由后重启服务器了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    相关资源
    最近更新 更多