0

I'm really confused because some of my routes when I use controllername_index_url are routing to /controllername/index while other's are routing to /controllername.

The main difference is that when I generate the index method when I create the controller through the command line

rails g controller controllerName1 index

the route then becomes /controller_name_1/index.

When I create the index manually after creating the controller, it becomes /controllername2

In my config/routes I am including my controllers like:

Rails.application.routes.draw do
  resources :controller_name_1
  resources :controller_name_2
end

And when I do a rails routes my routes look like

controller_name_1_index GET    /controller_name_1/index(.:format)                    controlle_name_1#index
controller_name_2_index GET    /controller_name_2(.:format)                             controller_name_2#index

Why is it automatically adding the routes differently? How can I make it so that regardless of it I generate the index methods on the command line or add them in after the fact, controller_name_index_url routes are always the same format? (I'm using ruby 2.4.0 and rails 5.1.2 if that's helpful)

beckah
  • 1,543
  • 6
  • 28
  • 61

1 Answers1

1

When you create an action at the command line a route is automatically generated for it.

$ rails g controller ones index

     create  app/controllers/ones_controller.rb
      route  get 'ones/index' # route helper is ones_index
     ...

The behavior is totally agnostic of the action you're creating. It could be any action name and Rails will do the same thing

$ rails g controller twos smorgas

     create  app/controllers/twos_controller.rb
      route  get 'twos/smorgas' # route helper is twos_smorgas
     ...

When you add resources to your routes

resources :ones

you automatically get all of the default REST route helpers and routes, no matter how you create any of the REST actions.

$ rake routes

          ones GET    /ones(.:format)                ones#index
               POST   /ones(.:format)                ones#create
       new_one GET    /ones/new(.:format)            ones#new
      edit_one GET    /ones/:id/edit(.:format)       ones#edit
           one GET    /ones/:id(.:format)            ones#show
               PATCH  /ones/:id(.:format)            ones#update
               PUT    /ones/:id(.:format)            ones#update
               DELETE /ones/:id(.:format)            ones#destroy

It's best to stick with Rails convention and use the default route helpers

ones_url
ones_path

# not ones_index_url

See this SO question if you want to disable the automatic route generation

m. simon borg
  • 2,515
  • 12
  • 20