简体   繁体   English

向URL而不是Rails API中的ID进行删除请求

[英]making a delete request to URL rather than ID in a rails api

i'm wondering if anyone can give me any advice. 我想知道是否有人可以给我任何建议。

I'm currently writing a rails API and although it doesn't seem like a best practice, rather than performing a DELETE call to 我目前正在编写一个Rails API,尽管这似乎不是最佳实践,而不是执行对DELETE的调用

localhost:3000/products/:id

id rather make it to 我宁愿去

localhost:3000/products/:url

and pass in the URL to be deleted, however i've currently got this but I keep getting a routing error. 并传递要删除的URL,但是我目前有这个,但是我一直收到路由错误。

DELETE '/products/:url', to: 'products#destroy'

is my current route for this, it is also specified above my 这是我目前的路线,也在我的上方指定

resources :products

sections. 部分。

My whole routes file: 我的整个路线文件:

AppName::Application.routes.draw do      
  resources :features do
  resources :feature_links
  end

  resources :wishlist_items

  resources :data_feeds
  get '/get_data_feeds', to: 'data_feeds#get_feed_url', as: 'feed_url'

  resources :genders

  resources :trends

  resources :sub_categories

  resources :color_tags

  resources :colors

  resources :categories

  delete '/products/:url', to: 'products#destroy'

  resources :products do
    member do
      get 'buy'
      post 'wish'
    end
  end
end

Any ideas? 有任何想法吗? Thanks in advance 提前致谢

If the url i'm sending the delete request to is http://localhost:3000/products/www.test.com I get the error No route matches [DELETE] "/products/www.test.com" if the url I sent the delete request to is http://localhost:3000/products/:url I get the error Couldn't find Product with 'id'=:url 如果我将删除请求发送到的URL是http://localhost:3000/products/www.test.com我将收到错误消息No route matches [DELETE] "/products/www.test.com"如果该URL No route matches [DELETE] "/products/www.test.com"我将删除请求发送到http://localhost:3000/products/:url我收到错误Couldn't find Product with 'id'=:url

My Destroy method code: 我的销毁方法代码:

 def destroy
    @product = Product.find(params[:url])
    @product.destroy
    respond_with(@product, status: 200)
 end

I think Rails is considering your URL parameter as the specification of the format of the response. 我认为Rails正在考虑将您的URL参数作为响应格式的规范。 You can override the constraints of the parameter as follows: 您可以按如下所示覆盖参数的约束:

constraints: { url: /[^\/]+/ }

This will make sure that the URL parameter can be anything except for / . 这将确保URL参数可以是/以外的任何值。 The whole route should look like this: 整个路线应如下所示:

delete "/products/:url", to: "products#destroy", constraints: { url: /[^\/]+/ }, as: :products_destroy_with_url

And use it like this: 并像这样使用它:

link_to "Destroy", products_destroy_with_url_path("www.test.com"), method: :delete

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM