Serge Pedroza
Serge Pedroza

Reputation: 2170

rename rails route

I have a route/path using CcpaAcknowledgmentsController

/ccpa_acknowledgments

I would like the route to be, BUT I would still like it to use the CcpaAcknowledgmentsController

/customers/ccpa_acknowledgments

Since I have these two routes...

resources :customers

resources :ccpa_acknowledgments

match '/customers/ccpa_acknowledgments', to: 'ccpa_acknowledgments#index', via: [:get]

I keep getting a conflict stating NoMethodError in CustomersController.

Is there a way to get the desired route I want without putting the method/code in the CustomersController?

Upvotes: 0

Views: 72

Answers (1)

Ursus
Ursus

Reputation: 30071

This is the way to do that

resources :customers do
  get :ccpa_acknowledgments, to: 'ccpa_acknowledgments#index', on: :collection
end

Inside the customers block for two reasons:

  • we are fine with the beginning of the path /customers
  • we don't want to mess with the other customers' routes. In this way your route inside the block is before the customers default routes and it's not seen as you are calling customers/:id with ccpa_acknowledgments as id because rails takes care of that for you defining that route before the show

Then

get :ccpa_acknowledgments

because we need the second part of the path /ccpa_acknowledgments

to: 'ccpa_acknowledgments#index'

we want to specify the controller and action pair, because we want to use the CcpaAcknowledgmentsController even though we're inside the customers block

on: :collection

because we don't want any :id inside our route. It's a route defined on the customers collection

alternative using resources as asked in the comment. Try

scope :customers do
  resources :ccpa_acknowledgments, only: :index 
end

but you need to put this before the resources :customers

Upvotes: 2

Related Questions