Is it more appropriate to generate a controller with subfolders and then define the routes manually, or to use the 'rails generate controller' command which creates routes automatically but does not organize the controller into subfolders?

In the development of a REST API with Rails, there is a question about the best way to structure controllers and routes. Two options are proposed:

  1. Generating the controller with subfolders and defining the routes manually:

rails generate controller api/v1/customer/create

Then, manually define the routes in the config/routes.rb file:

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      namespace :customer do
        post 'create', to: 'create#create'
      end
    end
  end
end
  1. Using the ‘rails generate controller’ command which creates routes automatically but does not organize the controller into subfolders.

rails generate controller api/v1/customer/create

In this case, the routes are generated automatically in the config/routes.rb file, but the controller is created at the root of the app/controllers folder.

What option is considered more appropriate and why?

Thanks!

Well, if your entire app only exists to serve the API, not mixing in any other concerns like http, then you are probably okay with option 2. The only thing that would concern me there is if you ever needed to keep v1 alive while you’re working on v2. In that case, you might need to step back one level and at least have controllers/v1/customers_controller.rb and controllers/v2/customers_controller.rb.

So you’d need to adjust the routes file after the fact to fix that. But at least initially, you could start without the v folder in your controllers. When it makes the views, how does it structure those? Are they nested or just living at app/views/customers ?

Hello @walterdavis , It is the backend, everything related to views and so on will be on the frontend side, thanks you so much for your reply!

The backend will be quite large and extensive that is why I am thinking of choosing to use option 1, thank you again for your response and your point of view.

1 Like

Where I was mentioning views, I was thinking of jbuilder templates, not front-end views. Those would need to be namespaced to match the controllers, so that the lookup paths would match.

@walterdavis Thanks for your help! I’m going to test everything and see how it goes.