从我的 JS 客户端对一个 URL/method 执行 PUT,另一个被击中

Doing a PUT to one URL/method from my JS client, another one getting hit

我正在尝试构建一个 API 端点,它采用多个我称为 Elements

的模型

调用转到 Api::V1::ElementsController Foo 方法。

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 操作时,我的终端出现以下错误

Started PUT "/v1/users/5/elements/element_update_multiple" for 10.0.2.2 at 2017-07-27 17:16:00 +0000 Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 ActiveRecord::SchemaMigration Load (0.4ms) SELECT "schema_migrations".* FROM "schema_migrations" Processing by Api::V1::ElementsController#update as JSON

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

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

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

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

要将路由添加到 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