You are previewing Learning Rails 3.

Learning Rails 3

Cover of Learning Rails 3 by Eric J Gruber... Published by O'Reilly Media, Inc.
  1. Learning Rails 3
  2. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  3. Preface
    1. Who This Book Is For
    2. Who This Book Is Not For
    3. What You’ll Learn
    4. Ruby and Rails Style
    5. Other Options
    6. Rails Versions
    7. If You Have Problems Making Examples Work
    8. If You Like (or Don’t Like) This Book
    9. Conventions Used in This Book
    10. Using Code Examples
    11. Safari® Books Online
    12. How to Contact Us
    13. Acknowledgments
  4. 1. Starting Up Ruby on Rails
    1. If You Run Windows, You’re Lucky
    2. Getting Started at the Command Line
    3. Starting Up Rails
    4. Test Your Knowledge
      1. Quiz
      2. Answers
  5. 2. Rails on the Web
    1. Creating Your Own View
    2. What Are All Those Folders?
    3. Adding Some Data
    4. How Hello World Works
    5. Adding Logic to the View
    6. Test Your Knowledge
      1. Quiz
      2. Answers
  6. 3. Adding Web Style
    1. I Want My CSS!
    2. Specifying Stylesheets
    3. Creating a Layout for a Controller
    4. Choosing a Layout from a Controller
    5. Sharing Template Data with the Layout
    6. Setting a Default Page
    7. Test Your Knowledge
      1. Quiz
      2. Answers
  7. 4. Managing Data Flow: Controllers and Models
    1. Getting Started, Greeting Guests
    2. Application Flow
    3. Keeping Track: A Simple Guestbook
      1. Connecting to a Database Through a Model
      2. Connecting the Controller to the Model
    4. Finding Data with ActiveRecord
    5. Test Your Knowledge
      1. Quiz
      2. Answers
  8. 5. Accelerating Development with Scaffolding and REST
    1. A First Look at Scaffolding
    2. REST and Controller Best Practices
      1. Websites and Web Applications
      2. Toward a Cleaner Approach
    3. Examining a RESTful Controller
      1. Index: An Overview of Data
      2. Show: Just One Row of Data
      3. New: A Blank Set of Data Fields
      4. Edit: Hand Me That Data, Please
      5. Create: Save Something New
      6. Put This Updated Record In
      7. Destroy It
    4. Escaping the REST Prison
    5. Test Your Knowledge
      1. Quiz
      2. Answers
  9. 6. Presenting Models with Forms
    1. More Than a Name on a Form
    2. Generating HTML Forms with Scaffolding
    3. Form as a Wrapper
    4. Creating Text Fields and Text Areas
    5. Labels
    6. Creating Checkboxes
    7. Creating Radio Buttons
    8. Creating Selection Lists
    9. Dates and Times
    10. Creating Helper Methods
    11. Test Your Knowledge
      1. Quiz
      2. Answers
  10. 7. Strengthening Models with Validation
    1. Without Validation
    2. The Original Model
    3. The Power of Declarative Validation
    4. Managing Secrets
      1. Customizing the Message
      2. Limiting Choices
      3. Testing Format with Regular Expressions
      4. Seen It All Before
      5. Numbers Only
    5. A Place on the Calendar
      1. Testing for Presence
    6. Beyond Simple Declarations
      1. Test It Only If
      2. Do It Yourself
    7. Test Your Knowledge
      1. Quiz
      2. Answers
  11. 8. Improving Forms
    1. Adding a Picture by Uploading a File
      1. File Upload Forms
      2. Model and Migration Changes
      3. Results
    2. Standardizing Your Look with Form Builders
      1. Supporting Your Own Field Types
      2. Adding Automation
      3. Integrating Form Builders and Styles
    3. Test Your Knowledge
      1. Quiz
      2. Answers
  12. 9. Developing Model Relationships
    1. Connecting Awards to Students
      1. Establishing the Relationship
      2. Supporting the Relationship
      3. Guaranteeing a Relationship
    2. Connecting Students to Awards
      1. Removing Awards When Students Disappear
      2. Counting Awards for Students
    3. Nesting Awards in Students
      1. Changing the Routing
      2. Changing the Controller
      3. Changing the Award Views
      4. Connecting the Student Views
      5. Is Nesting Worth It?
    4. Many-to-Many: Connecting Students to Courses
      1. Creating Tables
      2. Connecting the Models
      3. Adding to the Controllers
      4. Adding Routing
      5. Supporting the Relationship Through Views
    5. What’s Missing?
    6. Test Your Knowledge
      1. Quiz
      2. Answers
  13. 10. Managing Databases with Migrations
    1. What Migrations Offer You
    2. Migration Basics
      1. Migration Files
      2. Running Migrations Forward and Backward
    3. Inside Migrations
      1. Working with Tables
      2. Data Types
      3. Working with Columns
      4. Indexes
      5. Other Opportunities
    4. Test Your Knowledge
      1. Quiz
      2. Answers
  14. 11. Debugging
    1. Creating Your Own Debugging Messages
    2. Raising Exceptions
    3. Logging
    4. Working with Rails from the Console
    5. The Ruby Debugger
    6. Test Your Knowledge
      1. Quiz
      2. Answers
  15. 12. Testing
    1. Test Mode
    2. Setting Up a Test Database with Fixtures
    3. Unit Testing
    4. Functional Testing
      1. Calling Controllers
      2. Testing Responses
      3. Dealing with Nested Resources
    5. Integration Testing
    6. Beyond the Basics
    7. Test Your Knowledge
      1. Quiz
      2. Answers
  16. 13. Sessions and Cookies
    1. Getting Into and Out of Cookies
    2. Storing Data Between Sessions
    3. Test Your Knowledge
      1. Quiz
      2. Answers
  17. 14. Users and Authentication
    1. Installation
    2. Storing Identities
    3. Storing User Data
    4. Wiring OmniAuth into the Application
    5. Classifying Users
    6. More Options
    7. Test Your Knowledge
      1. Quiz
      2. Answers
  18. 15. Routing
    1. Creating Routes to Interpret URIs
      1. Specifying Routes with match
      2. Globbing
      3. Regular Expressions and Routing
      4. A Domain Default with root
      5. Named Routes
      6. Mapping Resources
      7. Nesting Resources
      8. Route Order and Priority
      9. Checking the Map
    2. Generating URIs from Views and Controllers
      1. Pointing url_for in the Right Direction
      2. Adding Options
    3. Infinite Possibilities
    4. Test Your Knowledge
      1. Quiz
      2. Answers
  19. 16. From CSS to SASS
    1. Getting Started
    2. Sassy Style
      1. Variables
      2. Mixins
      3. Nesting
    3. Making Everything Work Together
      1. Becoming Sassier
    4. Test Your Knowledge
      1. Quiz
      2. Answers
  20. 17. Managing Assets and Bundles
    1. The Junk Drawer
      1. Sprockets
      2. Dissecting The Pipeline
      3. Putting It All Together
      4. Bundler
    2. Test Your Knowledge
      1. Quiz
      2. Answers
  21. 18. Sending Code to the Browser: JavaScript and CoffeeScript
    1. Sending JavaScript to the Browser
    2. Simplifying with CoffeeScript
      1. Have Some Sugar with your CoffeeScript
      2. Converting to CoffeeScript
    3. Test Your Knowledge
      1. Quiz
      2. Answers
  22. 19. Mail in Rails
    1. Sending Mail Messages
    2. Receiving Mail
      1. Setup
      2. Processing Messages
    3. Test Your Knowledge
      1. Quiz
      2. Answers
  23. 20. Pushing Further into Rails
    1. Changing to Production Mode
    2. Deploying Is Much More Than Programming
    3. Joining the Rails Ecosystem
      1. Keep Up with Rails
      2. Ruby
      3. Working With and Around Rails
      4. Keep Exploring
  24. A. An Incredibly Brief Introduction to Ruby
    1. How Ruby Works
    2. How Rails Works
    3. Getting Started with Classes and Objects
    5. Variables, Methods, and Attributes
      1. Variables
      2. Methods
      3. Attributes
    6. Logic and Conditionals
      1. Operators
      2. if, else, unless, and elsif
      3. ?:
      4. case and when
      5. Loops
      6. Many More Possibilities
  25. B. An Incredibly Brief Introduction to Relational Databases
    1. Tables of Data
      1. Connecting Tables
      2. Using Tables to Connect Tables
      3. Granularity
    2. Databases, Tables, and Rails
  26. C. An Incredibly Brief Guide to Regular Expressions
    1. What Regular Expressions Do
    2. Starting Small
    3. The Simplest Expressions: Literal Strings
    4. Character Classes
    5. Escaping
    6. Modifiers
    7. Anchors
    8. Sequences, Repetition, Groups, and Choices
    9. Greed
    10. More Possibilities
  27. D. Glossary
    1. Speaking in Rails
  28. Index
  29. About the Authors
  30. Colophon
  31. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  32. Copyright
O'Reilly logo

Chapter 1. Starting Up Ruby on Rails

Before you can use Rails, you have to install it. Even if it’s already installed on your computer, you may need to consider upgrading it. In this chapter, we’ll take a look at some ways of installing Ruby, Rails, and the supporting infrastructure. Please feel very welcome to jump to whatever pieces of this section interest you and skip past those that don’t. Once the software is working, we’ll generate the basic Rails application, which will at least let you know if Rails is working. However you decide to set up Rails, in the end you’re going to have a structure like that shown in Figure 1-1.

The many components of a Rails installation

Figure 1-1. The many components of a Rails installation


All of these options are free. You don’t need to spend any money to use Rails, unless maybe you feel like buying a nice text editor.

The Rails welcome page

Figure 1-2. The Rails welcome page

If You Run Windows, You’re Lucky

Windows users (at last) can get a basic installation of Rails and supporting tools—everything you need to use this book—far more easily than anyone else. EngineYard’s Rails Installer, which you can get at , provides all the key components in a one-click installation. Visit the site, download the installer, and watch the video; after that, you should be ready to move ahead to Starting Up Rails.

Really, it’s that easy! (Well, except that you may have to tell Windows Defender not to block the port Rails uses to present the site. It’s also possible that you’ll have to install developer tools on newer versions of Windows.)


As this book was going to print, an initial version of RailsInstaller appeared for Mac OS X at Macintosh users may also be lucky now. Linux users still await a “coming soon” version.

Getting Started at the Command Line

Installing Rails by hand requires installing Ruby (preferably 1.9.2 or later), installing Gems, and then installing Rails. You will eventually also need to install SQLite, MySQL, or another relational database, though SQLite is already present on the Mac and in many Linux distributions.


As this book was going to print, an initial version of RailsInstaller appeared for Mac OS X at Macintosh users may also be lucky now, while Linux users still await a “coming soon” version.

Ruby comes standard on a number of Linux and Macintosh platforms. To see whether it’s there, and what version it has, enter ruby -v at the command prompt. You’ll want Ruby 1.8.7 or 1.9.2, so you may need to update it to a more recent version:

  • On Mac OS X, Snow Leopard (10.6) and Lion (10.7) include Ruby 1.8.7, and Leopard (10.5) includes Ruby 1.8.6, but the previous version of OS X included Ruby 1.8.2. If you’re on Tiger (10.4) or an earlier version of OS X, you’ll need to update Ruby itself, a challenge that’s beyond the scope of this book. You may want to investigate MacPorts, and the directions at For a more comprehensive installation, explore (You should ignore the versions of Rails installed with OS X - they’re guaranteed to be out of date.)

  • Most distributions of Linux include Ruby, but you’ll want to use your package manager to make sure it’s updated to 1.9.2. Some, notably Ubuntu and Debian, will name the gem command gem1.9.

  • For Windows, unless you’re a hardened tinkerer, it’s much easier to use Rails Installer. If you’re feeling strong, the One-Click Ruby Installer ( is probably your easiest option, though there are other alternatives, including Cygwin (, which brings a lot of the Unix environment to Windows.

A saner long-term approach to installing Ruby and Rails also includes installing rvm, the Ruby Version Manager, which frees you from having to worry about what version of Ruby your system decided it should have as well as giving you better options for managing a clean work environment. You can find out more about rvm at (It was created by Wayne E. Seguin, the same person who created Rails Installer.) If that doesn’t seem right to you, you can also find out more on how to install Ruby on a variety of platforms, see


If rvm isn’t for you, you may also want to explore rbenv (, a much smaller and simpler approach to switching between versions of Ruby.

RubyGems (often just called Gems) is also starting to come standard on a number of platforms, most recently on Mac OS X Leopard and Snow Leopard, but if you need to install Gems, see the RubyGems User Guide’s instructions at


If you use MacPorts, apt-get, or a similar package installer, you may want to use it only to install Ruby, and then proceed from the command line. You certainly can install Gems and Rails with these tools, but Gems can update itself, which can make for very confusing package update issues.

Once you have RubyGems installed, Rails and its many dependencies are just a command away (though the output has grown more verbose with every version of Rails):

~ simonstl$ gem install rails
	SimonMacBook:living_book_2010_rails_3 simonstl$ gem install rails
	Fetching: i18n-0.6.0.gem (100%)
	Fetching: [many more]..
	Depending on your version of ruby, you may need to install ruby rdoc/ri data:

	<= 1.8.6 : unsupported
	 = 1.8.7 : gem install rdoc-data; rdoc-data --install
	 = 1.9.1 : gem install rdoc-data; rdoc-data --install
	>= 1.9.2 : nothing to do! Yay!
	Fetching: railties-3.2.3.gem (100%)
	Fetching: bundler-1.0.22.gem (100%)
	Fetching: rails-3.2.3.gem (100%)
	Successfully installed i18n-0.6.0
	Successfully installed multi_json-1.1.0
	Successfully installed activesupport-3.2.3
	Successfully installed builder-3.0.0
	Successfully installed activemodel-3.2.3
	Successfully installed rack-1.4.1
	Successfully installed rack-cache-1.2
	Successfully installed rack-test-0.6.1
	Successfully installed journey-1.0.1
	Successfully installed hike-1.2.1
	Successfully installed tilt-1.3.3
	Successfully installed sprockets-2.1.2
	Successfully installed erubis-2.7.0
	Successfully installed actionpack-3.2.3
	Successfully installed arel-3.0.0
	Successfully installed tzinfo-0.3.31
	Successfully installed activerecord-3.2.3
	Successfully installed activeresource-3.2.3
	Successfully installed mime-types-1.17.2
	Successfully installed polyglot-0.3.3
	Successfully installed treetop-1.4.10
	Successfully installed mail-2.4.4
	Successfully installed actionmailer-3.2.3
	Successfully installed thor-0.14.6
	Successfully installed rack-ssl-1.3.2
	Successfully installed json-1.6.5
	Successfully installed rdoc-3.12
	Successfully installed railties-3.2.3
	Successfully installed bundler-1.0.22
	Successfully installed rails-3.2.3
	30 gems installed
	Installing ri documentation for i18n-0.6.0...
    [lots more documentation notices]

You may need to use sudo, which gives your command the power of the root (administrative) account, if you’re working in an environment that requires root access for the installation—otherwise, you can just type gem install rails. That will install the latest version of Rails, which may be more recent than 3.2.3, as well as all of its dependencies. gem install rails will install the latest official release of Rails, which at present is 3.2.3. It will not install any Rails betas. (To see which version of Rails is installed, enter rails -v at the command line.)

You may also need to install the sqlite3 gem, which isn’t automatically installed by the Rails gem but is needed for development. That’s gem install sqlite3.

If you’re ever wondering which gems (and which versions of gems) are installed, type gem list --local. For more information on gems, just type gem, or visit


You can see the documentation that gems have installed by running the command gem server, and visiting the URL (usually http://localhost:8808) that command reports. When you’re done, you can turn off the server with Ctrl-C.

Once you have Rails installed, you can create a Rails application easily from the command line. Here’s what it looks like in its extended glory, but you don’t need to read it every time:

~ $ rails new hello01
      create  README.rdoc
      create  Rakefile
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/images/rails.png
      create  app/assets/javascripts/application.js
      create  app/assets/stylesheets/application.css
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/mailers
      create  app/models
      create  app/views/layouts/application.html.erb
      create  app/mailers/.gitkeep
      create  app/models/.gitkeep
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  lib/assets
      create  lib/assets/.gitkeep
      create  log
      create  log/.gitkeep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  script
      create  script/rails
      create  test/fixtures
      create  test/fixtures/.gitkeep
      create  test/functional
      create  test/functional/.gitkeep
      create  test/integration
      create  test/integration/.gitkeep
      create  test/unit
      create  test/unit/.gitkeep
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor/assets/javascripts
      create  vendor/assets/javascripts/.gitkeep
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.gitkeep
      create  vendor/plugins
      create  vendor/plugins/.gitkeep
         run  bundle install
Fetching source index for
Using rake ( 
Using i18n (0.6.0) 
Using multi_json (1.1.0) 
Using activesupport (3.2.1) 
Using builder (3.0.0) 
Using activemodel (3.2.1) 
Using erubis (2.7.0) 
Using journey (1.0.1) 
Using rack (1.4.1) 
Using rack-cache (1.1) 
Using rack-test (0.6.1) 
Using hike (1.2.1) 
Using tilt (1.3.3) 
Using sprockets (2.1.2) 
Using actionpack (3.2.1) 
Using mime-types (1.17.2) 
Using polyglot (0.3.3) 
Using treetop (1.4.10) 
Using mail (2.4.1) 
Using actionmailer (3.2.1) 
Using arel (3.0.0) 
Using tzinfo (0.3.31) 
Using activerecord (3.2.1) 
Using activeresource (3.2.1) 
Using bundler (1.0.22) 
Using coffee-script-source (1.2.0) 
Using execjs (1.3.0) 
Using coffee-script (2.2.0) 
Using rack-ssl (1.3.2) 
Using json (1.6.5) 
Using rdoc (3.12) 
Using thor (0.14.6) 
Using railties (3.2.1) 
Installing coffee-rails (3.2.2) 
Installing jquery-rails (2.0.0) 
Using rails (3.2.1) 
Using sass (3.1.15) 
Installing sass-rails (3.2.4) 
Using sqlite3 (1.3.5) 
Using uglifier (1.2.3) 
Your bundle is complete! Use `bundle show [gemname]` to see where a 
bundled gem is installed.

This also gets longer and longer with each new version of Rails. Also, the bundle install piece may pause for a long moment.


Rails application directories are just ordinary directories. You can move them, obliterate them and start over, or do whatever you need to do with ordinary file-management tools. Each application directory is also completely independent—the general “Rails environment” just generates these applications.

Starting Up Rails

To start Rails, you’ll need to move into the directory you just created—cd hello01—and then issue your first command to get the WEBrick server busy running your application:

~ $ rails server
=> Booting WEBrick
=> Rails 3.2.1 application starting in development on
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-02-20 08:48:06] INFO  WEBrick 1.3.1
[2012-02-20 08:48:06] INFO  ruby 1.9.2 (2010-12-25) [x86_64-darwin10.5.0]
[2012-02-20 08:48:06] INFO  WEBrick::HTTPServer#start: pid=89377 port=3000

Rails is now running, and you can watch any errors it encounters through the extensive logging you’ll see in this window.


By default, rails server binds only to localhost at or, and the application isn’t visible from other computers. Normally, that’s a security feature, not a bug, though you can specify an address for the server to use with the -b option (and -p for a specific port) if you want to make it visible.

For more details on options for using rails server, just enter rails server -h.

If you now visit http://localhost:3000, you’ll see the same welcome screen shown previously in Figure 1-2. When you’re ready to stop Rails, you can just press Ctrl-C.


You frequently can leave Rails running while coding. In development mode, you can make many changes to your application with the server running, and you won’t have to restart the server to see them. If you change configuration, add scopes, or install gems, though, you’ll need to restart.

WEBrick ( is written in Ruby and bundled with recent releases of Ruby. It’s very convenient for Ruby development, with or without Rails. It’s an excellent testing server, but not designed for large scale deployment.

If you’ve never used Ruby before, now would be a good time to explore Appendix A, which teaches some key components of the language inside of a very simple Rails application.


Depending on how you set up your Rails environment and how you use Bundler, described in Chapter 17, you may need to preface your calls to rails, rake, and similar mechanisms with bundle exec to make sure you’re running exactly the version of the tools you expect to be running. If this seems like a lot of extra typing, visit to learn about binstubs, a way to avoid this.

Test Your Knowledge


  1. What’s the name of the Ruby application packaging utility and how do you install Rails with it?

  2. In what instances would you avoid WEBrick?

  3. Why should you install a particular version of Ruby on your platform when Ruby already comes installed?


  1. RubyGems, or just “gems,” which is run with the gem command, is Ruby’s application packager. To install the latest version of Rails and all its dependencies, just type gem install rails.

  2. WEBrick is great for testing your Rails applications, but definitely not the best choice for deployments where performance matters.

  3. Rails only works well on certain versions of Ruby, including 1.8.7 and 1.9.2.

The best content for your career. Discover unlimited learning on demand for around $1/day.