Before moving on, let’s consolidate the fundamental details of running the Rails generate controller
script and learn a few extra tricks you can use when creating views. Each time a new controller is generated, it creates a Ruby code file in the app/controllers directory, with a name matching the name you entered but all in lowercase, with any noninitial capitals that you specified being preceded by an underscore and _controller appended. So, if you entered SayHello, the controller file will be called say_hello_controller.rb. The controller will contain a class definition such as SayHelloController
. You may subsequently add to this class some “view methods” such as index
and bye
. Alternatively, you may use the generate
script to create one or more empty view methods automatically by including those view names when you execute the script.
For example, you could run this script:
Rails 3
rails generate controller SayHello index bye
Rails 2
ruby script/generate controller SayHello index bye
Rails will now create the file say_hello_controller.rb, containing this code:
class SayHelloController < ApplicationController def index end def bye end end
Whether or not you specify views, a folder in the /views directory is created with a name matching the controller (views/say_hello). In fact, the script also creates a few other files including some more Ruby files in the /helpers folder, but in our simple application you can ignore these files.
If you specified view names when running the controller script, some files with matching names and the extension .html.erb will be added to the appropriate view folder. For instance, if you entered the following command:
ruby script/generate controller SayHello xxx
the /views/say_hello directory should now contain a file called xxx.html.erb. If, on the other hand, you entered the following:
ruby script/generate controller Blather xxx bye snibbit
the views/blather directory should now contain three files: xxx.html.erb, bye.html.erb, and snibbit.html.erb.