Brian Law
Brian Law

Reputation: 639

Rails additional patch routes

I have CRUD already, and I want to add an additional Patch route, like this:

PATCH    /searches/:id(.:format)                                              searches#update

PATCH    /searches/sync(.:format)                                       searches/sync#perform

However, when I do api calls, it always return an error that says

ActiveRecord::RecordNotFound (Couldn't find Search with 'id'=sync)

Any ideas?

sync_controller

module Searches

  class SyncController < ApplicationController

    def perform
      search_ids = params[:search_ids]&.keys&.map { |key| params[:search_ids][key] } || []
      outcome = SearchSync.run(search_ids: search_ids, user: current_user)
      if outcome.success?
        render json: outcome.result
      else
        render json: outcome.errors.symbolic, status: 422
      end
    end

  end

end

Routes

resources :searches, only: [:index, :update, :destroy]
namespace :searches do
  patch '/sync', to: 'sync#perform'
end

Upvotes: 0

Views: 98

Answers (1)

Kaleem Ullah
Kaleem Ullah

Reputation: 56

I think you need to rename namespace from 'searches' to something else because its conflicting with resources :searches. If you don't want to change then you've to declare namespace above resources :searches.

Second, I doubt that PATCH is the right method in this case because PATCH should be used where there is an existing resource and we need to update it partially.

Upvotes: 1

Related Questions