Home arrow Ruby-on-Rails arrow Page 2 - Action Pack Controller Creation

Action Pack Controller Creation

In this fifth part of a multi-part series on the Action Pack library for Rails, you will learn how to configure routes for the event manager, and how to generate a controller. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
March 07, 2011
  1. · Action Pack Controller Creation
  2. · Generating a Controller

print this article

Action Pack Controller Creation - Generating a Controller
(Page 2 of 2 )

Itís time to create our first controller from scratch. If you havenít noticed already, Rails ships with generators for most common tasks, and controllers are no exception. The syntax for the controller generator is as follows:

$ ./script/generate controller ControllerName [actions] [options]

As a minimum, the controller generator takes the name of the controller as an argument, which you can specify using either CamelCase (sometimes called MixedCase) or underscore_case. The generator also takes an optional list of actions to generate. For every action you specify, youíll get an empty method stub in the controller and a template inapp/views/#{controller_name}. To see a list of all available options, you can run the generator without arguments.

Tip  The help output for the controller generator contains sample usage and options that youíre sure to find interesting. All of the generators (and most UNIX commands, for that matter) respond to the--helpargument (or variations thereof), so youíre encouraged to try it whenever youíre issuing a system command.

Generate the Users controller using the following command:

$ ./script/generate controller Users

exists  app/controllers/
exists  app/helpers/
create  app/views/users
exists  test/functional/
create  app/controllers/users_controller.rb
create test/functional/users_controller_test.rb
create  app/helpers/users_helper.rb

Take the time to read the output of the generator so you get a sense of all the files that were just created. Notice where the templates are located: in theapp/viewsdirectory, inside a subdirectory named for controller. In this case, since our controller is calledusers, our templates go insideapp/views/users. Letís open the newly minted controller file and have a look:

class UsersController < ApplicationController

Tip  Itís a convention in Rails that controller names should always be plural.

As you can see, all the generator gives us is an empty stub. If we want ouruserscontroller to do anything useful, weíll need to add an action and give it something to do. Letís create the first action on the controller now. Editusers_controller.rbso that it looks like Listing 6-2.

Listing 6-2. Updated app/controllers/users_controller.rb

class UsersController < ApplicationController
  def new
    @user = User.new

Before our action renders a view, we arrange for it to set an instance variable that the view can use. Just to refresh your memory, an instance variable is a special kind of Ruby variable that is unique to a given instance of a class, serving as a way for an object to maintain its state. Since views are, in essence, an extension of the controller object, they can access its instance variables directly (though not without some behind-the-scenes Ruby magic that Rails takes care of for you). For all intents and purposes, however, you can consider instance variables shared between controllers and views.

You can store any Ruby object in an instance variable, including strings, integers, models, hashes, and arrays. Since we want to initialize a new user, weíve created an instance variable called@userand hydrated it with a new instance of theUser model. If you recall from the Chapter 4, thenewmethod returns a new, unsaved object.


If youíre the curious sort (and, of course, you are), you might be wondering how the UsersController, a seemingly normal Ruby class, becomes a full-fledged Action Controller. Well, if you look closely, youíll notice that UsersController inherits from another class:
ApplicationController. In order to get a better picture of whatís going on, letís take a peek at
the ApplicationController class in app/controllers/application.rb.

class ApplicationController < ActionController::Base

The mystery is quickly solved. Our simple controller becomes an Action Controller by subclassing the ApplicationController class, itself a subclass of ActionController::Base. This is an example of inheritance and is common in object-oriented programming. When one class subclasses another, it inherits all the behavior and methods of the parent. In the case of our users controller, it inherits all the capabilities of the application controller. Likewise, ApplicationController inherits all the
capabilities of its parent, ActionController::Base. Itís the ActionController::Base class that effectively endows our users controller with its special abilities.

The application controller is the base from which all the controllers you make will inherit. Since itís the parent of all controllers in your application, itís a great place to put methods that you want accessible in every controller.

Please check back for the continuation of this series.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials