8.4. Working with Controllers

Routing is just the first part of the equation, with the second one being the actual code defined within controllers. If you are familiar with ASP.NET, this is conceptually similar to the Code Behind model, and a vital component of every Rails application. The final aim is to have separation of concerns and place just enough logic in the controller to orchestrate the application, while the heavy lifting is performed by the model layer and the presentation is delegated to the view.

8.4.1. Generating Controllers

In the examples presented so far, the controller was never created directly, but rather was generated as a consequence of running the scaffold generator. Controllers are contained within textual files so you could create a file in the right directory and define the code by hand. A more convenient and practical approach, though, is passing the controller argument to the generate script, as shown in the following example:

All controllers inherit from the ApplicationController class defined in application.rb. In Rails 2.3, this file is renamed as application_controller.rb to be more consistent with the naming convention of every other controller.

C:\projects\> rails chapter8 C:\projects\> cd chapter8 C:\projects\chapter8> ruby script/generate controller Account exists app/controllers/ exists app/helpers/ create app/views/account exists test/functional/ create app/controllers/account_controller.rb create test/functional/account_controller_test.rb ...

Get Ruby on Rails® for Microsoft Developers 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.