Configuring the default Rails routing route

TL DR

I would like to change the default behavior of Rails-resourceful routing to move the create path for all resources so that it is POST to /resources/new and not /resources .


Customization

Suppose a resourceful route is specified as follows:

 # routes.rb resources :events 


Actual routes to be created:

 $ rake routes Prefix Verb URI Pattern Controller#Action events GET /events(.:format) events#index POST /events(.:format) events#create new_event GET /events/new(.:format) events#new edit_event GET /events/:id/edit(.:format) events#edit event GET /events/:id(.:format) events#show PATCH /events/:id(.:format) events#update PUT /events/:id(.:format) events#update DELETE /events/:id(.:format) events#destroy 

NB that the create action is started by POST along the path /events .


Now, if I want to change this path, I can do it β€œmanually” based on each resource:

 # routes.rb # I've placed the routes in this order, and used `as: "new_event"`, # to avoid generating an `events_new` path helper. post 'events/new' => 'events#create', as: "new_event" resources :events, except: [:create] 


Here are the generated routes:

 $ rake routes Prefix Verb URI Pattern Controller#Action new_event POST /events/new(.:format) events#create events GET /events(.:format) events#index GET /events/new(.:format) events#new edit_event GET /events/:id/edit(.:format) events#edit event GET /events/:id(.:format) events#show PATCH /events/:id(.:format) events#update PUT /events/:id(.:format) events#update DELETE /events/:id(.:format) events#destroy 


Excellent! The create action is now triggered by POST along the path /events/new , and not along the path /events .

Each other route / helper behaves exactly the same as before, including a GET for the /events/new and new_event path / URL helpers.


Question

Instead of manually overriding each create action, is there a way to change the default path used for this particular action?

Otherwise, what other means could I use to change the heap of resourceful routes so that their action is transferred to /new , as mentioned above?

Thanks!

+6
source share
1 answer

You can make your life easier by adding a module that makes overriding for you in one place. eg:

 module MyResources def my_resources(resource_name, opts = {}, &block) opts = opts.merge(except: [:create]) resources(resource_name, opts, &block) post "#{resource_name}/new" => "#{resource_name}#create", as: "new_{resource_name}" end end ActionDispatch::Routing::Mapper.__send__ :include, MyResources 

Then in your route.rb you can do:

 my_resources :events 
+1
source

All Articles