【问题标题】:Doing a PUT to one URL/method from my JS client, another one getting hit从我的 JS 客户端对一个 URL/方法执行 PUT,另一个被击中
【发布时间】:2017-07-27 17:20:36
【问题描述】:

我正在尝试构建一个 API 端点,该端点采用多个我称之为 Elements 的模型

调用Api::V1::ElementsControllerFoo 方法。

scope module: :api, as: :api do
  namespace :v1 do
    resources :users, only: [:show, :update] do
        resources :elements
        put 'elements/element_update_multiple', to: 'elements#foo'

来自rake routes

api_v1_user_elements_element_update_multiple PUT      /v1/users/:user_id/elements/element_update_multiple(.:format) api/v1/elements#foo

但是,由于某种原因,当我从客户端对该路由执行 PUT 时,我的终端中出现以下错误

在 2017-07-27 17:16:00 +0000 为 10.0.2.2 开始 PUT "/v1/users/5/elements/element_update_multiple" 无法从 10.0.2.2 渲染控制台!允许的网络:127.0.0.1、::1、127.0.0.0/127.255.255.255 ActiveRecord::SchemaMigration Load (0.4ms) SELECT "schema_migrations".* FROM "schema_migrations" Api::V1::ElementsController#update as JSON 处理

它属于update 方法而不是foo 方法。知道为什么会这样吗?谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby rails-api


    【解决方案1】:

    这是因为您的路线文件中路线的顺序。你需要像这样切换它们:

    put 'elements/element_update_multiple', to: 'elements#foo'
    resources :elements
    

    routes.rb 文件是顺序敏感的,因此如果 Rails 在到达您的自定义 PUT 路由之前找到匹配的路由(在这种情况下,它会在您的资源路由中找到更新方法),它会先获取,并且永远不会到达您的自定义 PUT 路线。

    【讨论】:

      【解决方案2】:

      要将路由添加到resources,请尝试Adding Collection Routes,如下所示:

      scope module: :api, as: :api do
        namespace :v1 do
          resources :users, only: [:show, :update] do
              resources :elements do
                collection do
                  put 'element_update_multiple', to: 'elements#foo'
                end
              end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-06
        • 1970-01-01
        • 2011-11-11
        • 2015-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多