Name

Generators are used to create instant code for use in a Rails application. When you run the generator (using script/generate), new files (controllers, models, views, etc.) are generated and added to your application. You can also create custom generators. For more information on custom generators, watch Ryan Bates’s Railscast at http://railscasts.com/episodes/58.

To get more help on the generator script, type:

./script/generate --help

For help on a specific generator, type:

./script/generate [generator] --help

Rails comes with several built-in generators.

controller

Stubs out a new controller and its views. Pass the controller name, either CamelCased or under_scored, and a list of views as arguments.

To create a controller within a module, specify the controller name as a path, like parent_module/controller_name.

You can also create subcontrollers, which will inherit the parent controller by specifying the controller name as ParentControllerName::ChildControllerName. For example, if I have a controller named admin and I want a subcontroller named users that will inherit the authentication filter in the AdminController, I would type:

./script/generate controller Admin::Users

This generates a controller class in app/controllers/admin, view templates in app/views/admin/controller_name, a helper class in app/helpers/admin, and a functional test suite in test/functional/admin.

However, to make the child controller UsersController inherit AdminController, you will need to add the correct inheritance ...

Get Rails Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.