Tải bản đầy đủ (.pdf) (412 trang)

learning rails 3 [electronic resource]

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.46 MB, 412 trang )

Learning Rails 3
Simon St.Laurent, Edd Dumbill, and Eric J. Gruber
Beijing

Cambridge

Farnham

Köln

Sebastopol

Tokyo
Learning Rails 3
by Simon St.Laurent, Edd Dumbill, and Eric J. Gruber
Copyright © 2012 Simon St.Laurent, Edd Dumbill, Eric J. Gruber. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
Editor: Simon St.Laurent
Production Editor: Iris Febres
Proofreader: Jasmine Perez
Indexer: Lucie Haskins
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrators: Robert Romano, Rebecca Demarest,
and Jessamyn Read


July 2012: First Edition.
Revision History for the First Edition:
2012-07-11 First release
See for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Learning Rails 3, the image of the tarpans, and related trade dress are trademarks
of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
ISBN: 978-1-449-30933-6
[M]
1342467902
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
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 8
Test Your Knowledge 9
Quiz 9
Answers 9
2. Rails on the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Creating Your Own View 11
What Are All Those Folders? 14
Adding Some Data 16
How Hello World Works 18

Adding Logic to the View 20
Test Your Knowledge 22
Quiz 22
Answers 22
3. Adding Web Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
I Want My CSS! 23
Specifying Stylesheets 28
Creating a Layout for a Controller 29
Choosing a Layout from a Controller 31
Sharing Template Data with the Layout 33
Setting a Default Page 34
Test Your Knowledge 36
Quiz 36
Answers 36
iii
4. Managing Data Flow: Controllers and Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Getting Started, Greeting Guests 37
Application Flow 42
Keeping Track: A Simple Guestbook 44
Connecting to a Database Through a Model 44
Connecting the Controller to the Model 47
Finding Data with ActiveRecord 52
Test Your Knowledge 54
Quiz 54
Answers 54
5. Accelerating Development with Scaffolding and REST . . . . . . . . . . . . . . . . . . . . . . . . 57
A First Look at Scaffolding 57
REST and Controller Best Practices 61
Websites and Web Applications 61
Toward a Cleaner Approach 63

Examining a RESTful Controller 64
Index: An Overview of Data 69
Show: Just One Row of Data 71
New: A Blank Set of Data Fields 71
Edit: Hand Me That Data, Please 72
Create: Save Something New 72
Put This Updated Record In 74
Destroy It 75
Escaping the REST Prison 76
Test Your Knowledge 76
Quiz 76
Answers 77
6. Presenting Models with Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
More Than a Name on a Form 79
Generating HTML Forms with Scaffolding 80
Form as a Wrapper 84
Creating Text Fields and Text Areas 87
Labels 89
Creating Checkboxes 90
Creating Radio Buttons 91
Creating Selection Lists 93
Dates and Times 95
Creating Helper Methods 97
Test Your Knowledge 100
Quiz 100
Answers 100
iv | Table of Contents
7. Strengthening Models with Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Without Validation 103
The Original Model 106

The Power of Declarative Validation 106
Managing Secrets 109
Customizing the Message 109
Limiting Choices 111
Testing Format with Regular Expressions 112
Seen It All Before 112
Numbers Only 113
A Place on the Calendar 114
Testing for Presence 115
Beyond Simple Declarations 115
Test It Only If 115
Do It Yourself 116
Test Your Knowledge 117
Quiz 117
Answers 117
8. Improving Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Adding a Picture by Uploading a File 119
File Upload Forms 120
Model and Migration Changes 120
Results 126
Standardizing Your Look with Form Builders 129
Supporting Your Own Field Types 130
Adding Automation 132
Integrating Form Builders and Styles 134
Test Your Knowledge 137
Quiz 137
Answers 138
9. Developing Model Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Connecting Awards to Students 140
Establishing the Relationship 140

Supporting the Relationship 141
Guaranteeing a Relationship 145
Connecting Students to Awards 146
Removing Awards When Students Disappear 146
Counting Awards for Students 147
Nesting Awards in Students 148
Changing the Routing 149
Changing the Controller 150
Table of Contents | v
Changing the Award Views 153
Connecting the Student Views 156
Is Nesting Worth It? 158
Many-to-Many: Connecting Students to Courses 159
Creating Tables 159
Connecting the Models 161
Adding to the Controllers 162
Adding Routing 164
Supporting the Relationship Through Views 164
What’s Missing? 172
Test Your Knowledge 172
Quiz 172
Answers 173
10.
Managing Databases with Migrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
What Migrations Offer You 175
Migration Basics 176
Migration Files 177
Running Migrations Forward and Backward 178
Inside Migrations 180
Working with Tables 181

Data Types 181
Working with Columns 183
Indexes 183
Other Opportunities 184
Test Your Knowledge 185
Quiz 185
Answers 185
11. Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Creating Your Own Debugging Messages 187
Raising Exceptions 188
Logging 188
Working with Rails from the Console 190
The Ruby Debugger 195
Test Your Knowledge 199
Quiz 199
Answers 199
12. Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Test Mode 201
Setting Up a Test Database with Fixtures 202
Unit Testing 206
vi | Table of Contents
Functional Testing 212
Calling Controllers 214
Testing Responses 215
Dealing with Nested Resources 216
Integration Testing 218
Beyond the Basics 220
Test Your Knowledge 221
Quiz 221
Answers 221

13. Sessions and Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Getting Into and Out of Cookies 223
Storing Data Between Sessions 230
Test Your Knowledge 235
Quiz 235
Answers 235
14. Users and Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Installation 237
Storing Identities 239
Storing User Data 239
Wiring OmniAuth into the Application 240
Classifying Users 248
More Options 255
Test Your Knowledge 256
Quiz 256
Answers 256
15. Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Creating Routes to Interpret URIs 258
Specifying Routes with match 258
Globbing 260
Regular Expressions and Routing 261
A Domain Default with root 261
Named Routes 262
Mapping Resources 263
Nesting Resources 264
Route Order and Priority 265
Checking the Map 265
Generating URIs from Views and Controllers 266
Pointing url_for in the Right Direction 266
Adding Options 267

Infinite Possibilities 267
Table of Contents | vii
Test Your Knowledge 268
Quiz 268
Answers 268
16. From CSS to SASS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Getting Started 271
Sassy Style 272
Variables 272
Mixins 274
Nesting 275
Making Everything Work Together 276
Becoming Sassier 279
Test Your Knowledge 280
Quiz 280
Answers 280
17. Managing Assets and Bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
The Junk Drawer 281
Sprockets 282
Dissecting The Pipeline 283
Putting It All Together 283
Bundler 286
Test Your Knowledge 290
Quiz 290
Answers 290
18. Sending Code to the Browser: JavaScript and CoffeeScript . . . . . . . . . . . . . . . . . . . 291
Sending JavaScript to the Browser 292
Simplifying with CoffeeScript 293
Have Some Sugar with your CoffeeScript 295
Converting to CoffeeScript 297

Test Your Knowledge 298
Quiz 298
Answers 298
19. Mail in Rails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
Sending Mail Messages 299
Receiving Mail 304
Setup 305
Processing Messages 305
Test Your Knowledge 308
Quiz 308
Answers 308
viii | Table of Contents
20. Pushing Further into Rails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Changing to Production Mode 309
Deploying Is Much More Than Programming 310
Joining the Rails Ecosystem 313
Keep Up with Rails 313
Ruby 313
Working With and Around Rails 314
Keep Exploring 314
A. An Incredibly Brief Introduction to Ruby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
B. An Incredibly Brief Introduction to Relational Databases . . . . . . . . . . . . . . . . . . . . 335
C.
An Incredibly Brief Guide to Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
D. Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Table of Contents | ix

Preface
Everyone cool seems to agree: Ruby on Rails is an amazing way to build web

applications. Ruby is a powerful and flexible programming language, and Rails takes
advantage of that flexibility to build a web application framework that takes care of a
tremendous amount of work for the developer. Everything sounds great!
Except, well… all the Ruby on Rails books talk about this “Model-View-Controller”
thing, and they start deep inside the application, close to the database, most of the time.
From an experienced Rails developer’s perspective, this makes sense—the framework’s
power lies largely in making it easy for developers to create a data model quickly, layer
controller logic on top of that, and then, once all the hard work is done, put a thin layer
of interface view on the very top. It’s good programming style, and it makes for more
robust applications. Advanced Ajax functionality seems to come almost for free!
From the point of view of someone learning Ruby on Rails, however, that race to show
off Rails’ power can be extremely painful. There’s a lot of seemingly magical behavior
in Rails that works wonderfully—until one of the incantations isn’t quite right and
figuring out what happened means unraveling all that work Rails did. Rails certainly
makes it easier to work with databases and objects without spending forever thinking
about them, but there are a lot of things to figure out before that ease becomes obvious.
If you’d rather learn Ruby on Rails more slowly, starting from pieces that are more
familiar to the average web developer and then moving slowly into controllers and
models, you’re in the right place. You can start from the HTML you already likely know,
and then move more deeply into Rails’ many interlinked components.
This updated version of Learning Rails covers version 3.2. There are
substantial changes from earlier versions. Rails itself keeps changing,
even in ways that affect beginners.
Who This Book Is For
You’ve probably been working with the Web for long enough to know that writing web
applications always seems more complicated than it should be. There are lots of parts
xi
to manage, along with lots of people to manage, and hopefully lots of visitors to please.
Ruby on Rails has intrigued you as one possible solution to that situation.
You may be a designer who’s moving toward application development or a developer

who combines some design skills with some programming skills. You may be a
programmer who’s familiar with HTML but who lacks the sense of grace needed to
create beautiful design—that’s a fair description of one of the authors of this book,
anyway. Wherever you’re from, whatever you do, you know the Web well and would
like to learn how Rails can make your life easier.
The only mandatory technical prerequisite for reading this book is direct familiarity
with HTML and a general sense of how programming works. You’ll be inserting Ruby
code into that HTML as a first step toward writing Ruby code directly, so understanding
HTML is a key foundation. (If you don’t know Ruby at all, you probably want to look
over Appendix A or at least keep it handy for reference.)
Cascading Style Sheets (CSS) will help you make that HTML look a lot nicer, but it’s
not necessary for this book. Similarly, a sense of how JavaScript works may help.
Experience with other templating languages (like PHP, ASP, and ASP.NET) can also
help, but it isn’t required.
You also need to be willing to work from the command line sometimes. The commands
aren’t terribly complicated, but they aren’t (yet) completely hidden behind a graphical
interface.
Who This Book Is Not For
We don’t really want to cut anyone out of the possibility of reading this book, but there
are some groups of people who aren’t likely to enjoy it. Model-View-Controller purists
will probably grind their teeth through the first few chapters, and people who insist
that data structures are at the heart of a good application are going to have to wait an
even longer time to see their hopes realized. If you consider HTML just a nuisance that
programmers have to put up with, odds are good that this book isn’t for you. Most of
the other Ruby on Rails books, though, are written for people who want to start from
the model!
Also, people who are convinced that Ruby and Rails are the one true way may have
some problems with this book, which spends a fair amount of time warning readers
about potential problems and confusions they need to avoid. Yes, once you’ve worked
with Ruby and Rails for a while, their elegance is obvious. However, reaching that level

of comfort and familiarity is often a difficult road. This book attempts to ease as many
of those challenges as possible by describing them clearly.
xii | Preface
What You’ll Learn
Building a Ruby on Rails application requires mastering a complicated set of skills. You
may find that—depending on how you’re working with it, and who you’re working
with—you only need part of this tour. That’s fine. Just go as far as you think you’ll need.
At the beginning, you’ll need to install Ruby on Rails. We’ll explore different ways of
doing this, with an emphasis on easier approaches to getting Ruby and Rails
operational.
Next, we’ll create a very simple Ruby on Rails application, with only a basic view and
then a controller that does a very few things. From this foundation, we’ll explore ways
to create a more sophisticated layout using a variety of tools, learning more about Ruby
along the way.
Once we’ve learned how to present information, we’ll take a closer look at controllers
and what they can do. Forms processing is critical to most web applications, so we’ll
build a few forms and process their results, moving from the simple to the complex.
Forms can do interesting things without storing data, but after a while it’s a lot more
fun to have data that lasts for more than just a few moments. The next step is setting
up a database to store information and figuring out how the magic of Rails’
ActiveRecord makes it easy to create code that maps directly to database structures—
without having to think too hard about database structures or SQL.
Once we have ActiveRecord up and running, we’ll explore scaffolding and its possi-
bilities. Rails scaffolding not only helps you build applications quickly, it helps you
learn to build them well. The RESTful approach that Rails emphasizes will make it
simpler for you to create applications that are both attractive and maintainable. For
purposes of illustration, using scaffolding also makes it easier to demonstrate one task
at a time, which we hope will make it easier for you to understand what’s happening.
Ideally, at this point, you’ll feel comfortable with slightly more complicated data mod-
els, and we’ll take a look at applications that need to combine data in multiple tables.

Mixing and matching data is at the heart of most web applications.
We’ll also take a look at testing and debugging Rails code, a key factor in the frame-
work’s success. Migrations, which make it easy to modify your underlying data
structures (and even roll back those changes if necessary), are another key part of Rails’
approach to application maintainability.
The next step will be to add some common web applications elements like sessions and
cookies, as well as authentication. Rails (with the help of gems for authentication) can
manage a lot of this work for you.
We’ll also let Rails stretch its legs a bit, showing off its recent support for Syntactically
Awesome Stylesheets (Sass), CoffeeScript scripting, bundle management, and sending
email messages.
Preface | xiii
By the end of this tour, you should be comfortable with working in Ruby on Rails. You
may not be a Rails guru yet, but you’ll be ready to take advantage of all of the other
resources out there for becoming one.
Ruby and Rails Style
It’s definitely possible to write Ruby on Rails code in ways that look familiar to
programmers from other languages. However, that code often isn’t really idiomatic
Ruby, as Ruby programmers have chosen other paths. In general, this book will always
try to introduce new concepts using syntax that’s likely to be familiar to developers
from other environments, and then explain what the local idiom does. You’ll learn to
write idiomatic Ruby that way (if you want to), and at the same time you’ll figure out
how to read code from the Ruby pros.
We’ve tried to make sure that the code we present is understandable to those without
a strong background in Ruby. Ruby itself is worth an introductory book (or several),
but the Ruby code in a lot of Rails applications is simple, thanks to the hard work the
framework’s creators have already put into it. You may want to install Rails in Chap-
ter 1, and then explore Appendix: “An Incredibly Brief Introduction to Ruby” before
diving in.
Other Options

There are lots of different ways to learn Rails. Some people want to learn Ruby in detail
before jumping into a framework that uses it. That’s a perfectly good option, and if you
want to start that way, you should explore the following books:
• Learning Ruby by Michael Fitzgerald (O’Reilly, 2007)
• The Ruby Programming Language by David Flanagan and Yukhiro Matsumoto
(O’Reilly, 2008)
• Ruby Pocket Reference by Michael Fitzgerald (O’Reilly, 2007)
• Programming Ruby, Third Edition by Dave Thomas with Chad Fowler and Andy
Hunt (Pragmatic Programmers, 2008)
• The Well-Grounded Rubyist by David A. Black (Manning, 2009)
• Eloquent Ruby by Russ Olsen (Addison-Wesley, 2011)
• Metaprogramming Ruby by Paolo Perrotta (Pragmatic Programmers, 2010)
You may also want to supplement (or replace) this book with other books on Rails. If
you want some other resources, you can explore:
• For maximum excitement, try a training tool that
includes video and exercises.
xiv | Preface
• Try for all kinds of detailed programming demonstrations in
a video format.
• Ruby on Rails 3 Tutorial by Michael Hartl (Addison-Wesley, 2010), provides a
faster-moving introduction that covers many more extensions for Rails.
• The Rails 3 Way by Obie Fernandez (Addison-Wesley, 2010), takes a big-book
reference approach for developers who already know their way.
• Agile Web Development with Rails, Fourth Edition, (Pragmatic Programmers,
2010), by Sam Ruby, Dave Thomas, and David Heinemeier Hansson gives a de-
tailed explanation of a wide range of features.
Ideally, you’ll want to make sure that whatever books or online documentation you
use cover at least Rails 3.0 (or later). Rails’ perpetual evolution has unfortunately made
it dangerous to use a lot of formerly great but now dated material (some of it works,
some of it doesn’t).

Finally, key resources you should always explore are the Ruby on Rails Guides (http://
guides.rubyonrails.org/), which provide an excellent and well-updated overview for a
lot of common topics. Sometimes they leave gaps or demand more background
knowledge than beginners have, but they’re a wonderful layer of documentation at a
level above the basic (though also useful) API documentation at yonrails
.org/.
Rails Versions
The Rails team is perpetually improving Rails and releasing new versions. This book
was updated for Rails 3.2.3 and Ruby 1.9.2.
If You Have Problems Making Examples Work
When you’re starting to use a new framework, error messages can be hard, even
impossible, to decipher. We’ve included occasional notes in the book about particular
errors you might see, but it seems very normal for different people to encounter different
errors as they work through examples. Sometimes it’s the result of skipping a step or
entering code just a little differently than it was in the book. It’s probably not the result
of a problem in Rails itself, even if the error message seems to come from deep in the
framework. That isn’t likely an error in the framework, but much more likely a problem
the framework is having in figuring out how to deal with the unexpected code it just
encountered.
If you find yourself stuck, here are a few things you should check:
What version of Ruby are you running?
You can check by entering ruby -v. All of the examples in this book were written
with Ruby 1.9.2. You can also use Ruby 1.8.7 with Rails, but many of the examples
Preface | xv
here (especially those using hashes) may not always work for you. Versions of Ruby
older than 1.8.7 may cause problems for Rails 3.x, and even version 1.9.1 of Ruby
causes problems. Chapter 1 explores how to install Ruby, but you may need to
find documentation specific to your specific operating system and environment.
What version of Rails are you running?
You can check by running rails -v. You might think that you should be able to

use the examples here with any version of Rails 3.x, but Rails keeps changing in
ways that break even simple code even among the 3.x versions. The examples on
the book’s site include a number of versions from Rails 2.1 to Rails 3.2. If you’re
running a version of Rails other than 3.2, especially an earlier version, you will
encounter problems.
Are you calling the program the right way?
Linux and Mac OS X both use a forward slash, /, as a directory separator, whereas
Windows uses a backslash, \. This book uses the forward slash, but if you’re in
Windows, you may need to use the backslash. Leaving out an argument can also
produce some really incomprehensible error messages.
Is the database connected?
By default, Rails expects you to have SQLite up and running, though some instal-
lations use MySQL or other databases. If you’re getting errors that have “sql” in
them somewhere, it’s probably the database. Check that the database is installed
and running, that the settings in database.yml are correct, and that the permissions,
if any, are set correctly.
Are all of the pieces there?
Most of the time, assembling a Rails application, even a simple one, requires
modifying multiple files—at least a view and a controller. If you’ve only built a
controller, you’re missing a key piece you need to see your results; if you’ve only
built a view, you need a controller to call it. As you build more and more complex
applications, you’ll need to make sure you’ve considered routing, models, and
maybe even configuration and plug-ins. What looks like a simple call in one part
of the application may depend on pieces elsewhere.
Eventually, you’ll know what kinds of problems specific missing pieces cause, but
at least at first, try to make sure you’ve entered complete examples before running
them.
It’s also possible to have files present but with the wrong permissions set. If you
know a file is there, but Rails can’t seem to get to it, check to make sure that
permissions are set correctly.

Did you save all the files?
Of course this never happens to you. However, making things happen in Rails often
means tinkering with multiple files at the same time, and it’s easy to forget to save
one as you move along. This can be especially confusing if it was a configuration
or migration file. Always take a moment to make sure everything you’re editing
has been saved before trying to run your application.
xvi | Preface
Are your routes right?
If you can’t get a page to come up, you probably have a problem with your routes.
This is a more common problem when you’re creating controllers directly, as you
will be up through Chapter 4, rather than having Rails generate scaffolding. Check
config/routes.rb.
Is everything named correctly?
Rails depends on naming conventions to establish connections between data and
code without you having to specify them explicitly. This works wonderfully, until
you have a typo somewhere obscure. Rails also relies on a number of Ruby con-
ventions for variables, prefacing instance variables with @ or symbols with :. These
special characters make a big difference, so make sure they’re correct.
Is the Ruby syntax right?
If you get syntax errors, or sometimes even if you get a nil object error, you may
have an extra space, missing bracket, or similar issue. Ruby syntax is extremely
flexible, so you can usually ignore the discipline of brackets, parentheses, or
spaces—but sometimes it really does matter.
Is another Rails app running?
Jumping quickly between programs can be really confusing. In a normal develop-
ment cycle, you’ll just have one app running, and things just work. When you’re
reading a book, especially if you’re downloading the examples, it’s easy to start an
app, close the window you use to explore it, and forget it’s still running underneath.
Definitely stop one server before running another while you’re exploring the apps
in this book.

Are you running the right program?
Yes, this sounds weird. When you’re developing real programs, it makes sense to
leave the server running to check back and forth with your changes. If you’re testing
out a lot of small application examples quickly, though, you may have problems.
Definitely leave the server running while you’re working within a given example,
but stop it when you change chapters or set off to create a new application with
the rails command.
Does your model specify attr_accessible?
Rails tightened its security rules in Rails 3.2, requiring that models include an
attr_accessible declaration at the start, identifying which fields can be reached
through Rails. Older code, even code from earlier versions of this book, generally
didn’t do this. If you get error messages like “Can’t mass-assign protected
attributes,” this is likely the problem.
Did the authors just plain screw up?
Obviously, we’re working hard to ensure that all of the code in this book runs
smoothly the first time, but it’s possible that an error crept through. You’ll want
to check the errata, described in the next section, and download sample code,
which will be updated for errata.
Preface | xvii
It’s tempting to try Googling errors to find a quick fix. Unfortunately, the issues just
described are more likely to be the problem than something else that has clear
documentation. The Rails API documentation ( might be
helpful at times, especially if you’re experimenting with extending an example. There
shouldn’t be much out there, though, beyond the book example files themselves that
you can download to fix an example.
If You Like (or Don’t Like) This Book
If you like—or don’t like—this book, by all means, please let people know. Amazon
reviews are one popular way to share your happiness (or lack of happiness), or you can
leave reviews on the site for this book:
/>There’s also a link to errata there. Errata gives readers a way to let us know about typos,

errors, and other problems with the book. The errata will be visible on the page
immediately, and we’ll confirm it after checking it out. O’Reilly can also fix errata in
future printings of the book and on Safari, making for a better reader experience pretty
quickly.
We hope to keep this book updated for future versions of Rails and will also incorporate
suggestions and complaints into future editions.
Conventions Used in This Book
The following font conventions are used in this book:
Italic
Indicates pathnames, filenames, and program names; Internet addresses, such as
domain names and URLs; and new items where they are defined.
Constant width
Indicates command lines and options that should be typed verbatim; names and
keywords in programs, including method names, variable names, and class names;
and HTML element tags.
Constant width bold
Indicates emphasis in program code lines.
Constant width italic
Indicates text that should be replaced with user-supplied values.
This icon signifies a tip, suggestion, or general note.
xviii | Preface
This icon indicates a warning or caution.
Using Code Examples
The code examples for this book, which are available from />Rails3, come in two forms. One is a set of examples, organized by chapter, with each
example numbered and named. These examples are referenced from the relevant chap-
ter. The other form is a dump of all the code from the book, in the order it was presented
in the book. That can be helpful if you need a line that didn’t make it into the final
example, or if you want to cut and paste pieces as you walk through the examples.
Hopefully, the code will help you learn.
So far, the code examples for this electronic version of the book have stayed in sync

with the code examples for the print book, updated for errata.
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “Learning Rails 3 by Simon St.Laurent,
Edd Dumbill, and Eric J. Gruber. Copyright 2012 Simon St.Laurent, Edd Dumbill, and
Eric Gruber, 978-1-449-30933-6.”
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at
Safari® Books Online
Safari Books Online (www.safaribooksonline.com) is an on-demand digital
library that delivers expert content in both book and video form from the
world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and cre-
ative professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi-
zations, government agencies, and individuals. Subscribers have access to thousands
Preface | xix
of books, training videos, and prepublication manuscripts in one fully searchable
database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-
Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco
Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe
Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course

Technology, and dozens more. For more information about Safari Books Online, please
visit us online.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:
/>To comment or ask technical questions about this book, send email to:

For more information about our books, courses, conferences, and news, see our website
at .
Find us on Facebook: />Follow us on Twitter: />Watch us on YouTube: />Acknowledgments
Thanks to Mike Loukides for thinking that Rails could use a new and different ap-
proach, and for supporting this project along the way. Tech reviewers Gregg Pollack,
Shelley Powers, Mike Fitzgerald, Eric Berry, David Schruth, Mike Hendrickson, and
Mark Levitt all helped improve the first edition of the book tremendously. For this
edition, Aaron Sumner, David DeMello, and Alan Harris went through the details
carefully, finding many changes we’d overlooked and making helpful suggestions. The
rubyonrails-talk group provided regular inspiration, as did the screencasts and podcasts
at />xx | Preface
Edd Dumbill wishes to thank his lovely children, Thomas, Katherine, and Peter, for
bashing earnestly on the keyboard, and his coauthor, Simon St.Laurent, for his patient
encouragement in writing this book.
Simon St.Laurent wants to thank Angelika St.Laurent for her support over the course
of writing this, even when it interfered with dinner, and Sungiva and Konrad St.Laurent

for their loudly shouted suggestions. Simon would also like to thank Edd Dumbill for
his initial encouragement and for making this book possible.
Eric would like to thank his lovely wife for enduring many late-night endeavors to learn
about this wonderful world of code, his parents and sister for always encouraging him
to find his own path, his community of designers and developers in the Lawrence area,
Aaron Sumner for being a patient guide in the Ruby world, and his children, who inspire
him to learn how to code well enough to teach it to them (if that’s what they want).
We’d all like to thank Jasmine Perez for cleaning up our prose, Iris Febres for getting
this book through production, and Lucie Haskins for the patient work it takes to build
an index.
Preface | xxi

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.
Figure 1-1. The many components of a Rails installation
1

×