Creating Rails Controller In Sub-directory

1.2k views Asked by At

How do I create a rails Events controller in a different directory other than the default:

app/controllers/events_controller.rb

I need to create in app/controllers/api/events_controller.rb

I created the api sub-directory and did cd in terminal to api. When I created the controller it still generated in the default app/controllers/.

Thanks.

2

There are 2 answers

0
Ecnalyr On

You can namespace your controllers (generated like this: rails g controller API::Events).

Put your controller in the api directory within your controllers directory and name the controller's class like this:

class API::EventsController < ApplicationController

More details discussed here: https://stackoverflow.com/a/9946410/1026898


If that is not what you want to do, rails tends to lean in the direction of not putting that controller in a different directory.

It doesn't hurt anything to do so, it's just a bit odd. The rails generators, by default, are built to put the controllers in the conventional directory.

If you want to change where they are generated you will have to update the generator.

0
AbM On

To do that with rails generators:

rails g controller API::Events