Chapter 4. Controlling Data Flow: Controllers and Models
It’s time to meet the key player in Rails applications. Controllers are the components that determine how to respond to user requests and coordinate responses. They’re at the heart of what many people think of as “the program” in your Rails applications, though in many ways they’re more of a switchboard. They connect the different pieces that do the heavy lifting, providing a focal point for application development. The model is the foundation of your application’s data structures, which will let you get information into and out of your databases.
Getting Started, Greeting Guests
Controllers are Ruby objects. They’re stored in the app/controllers directory of your
application. Each controller has a name, and the object inside of the
controller file is called nameController.
Demonstrating controllers without getting tangled in all of Rails’ other components is difficult, so for an initial tour, the application will be incredibly simple. (You can see the first version of it in ch04/guestbook001.) Guestbooks were a common (if kind of annoying) feature on early websites, letting visitors “sign in” so that the site could tell who’d been there. (The idea has since evolved into much more sophisticated messaging, like Facebook’s “wall.”)
To get started, create a new Rails application, as we did in Chapter 1. If you’re working from the command line, type:
rails guestbook
Rails will create the usual pile of files and folders. Next, you’ll ...