Reputation: 6998
I'm trying to build an API endpoint that takes multiple of a model I call Element
s
The call goes to Api::V1::ElementsController
to the Foo
method.
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'
From rake routes
api_v1_user_elements_element_update_multiple PUT /v1/users/:user_id/elements/element_update_multiple(.:format) api/v1/elements#foo
However, for some reason when I do a PUT to that route from my client, I get the following error in my terminal
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
It's falling into the update
method rather than the foo
method. Any idea why this is happening? Thanks!
Upvotes: 2
Views: 42
Reputation: 8290
To add routes to a resources
try Adding Collection Routes like so:
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
Upvotes: 0
Reputation: 6942
It's because of the order of the routes in your routes file. You need to switch them around like this:
put 'elements/element_update_multiple', to: 'elements#foo'
resources :elements
routes.rb
files are order-sensitive, so if Rails finds a matching route before it hits your custom PUT route (in this case it finds the update method in your resource routes) it will take that first, and never get to your custom PUT route.
Upvotes: 1