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.
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 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.)
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.
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.
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 possibilities. 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 models, 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 framework’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.
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.
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 Chapter 1, and then explore Appendix: “An Incredibly Brief Introduction to Ruby” before diving in.
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 http://railsforzombies.com/, a training tool that includes video and exercises.
Try http://railscasts.com/ 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 detailed 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 http://api.rubyonrails.org/.
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.
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:
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 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.
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.
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.
By default, Rails expects you to have SQLite up and running, though some installations 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.
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.
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.
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.
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 conventions for variables,
prefacing instance variables with
@ or symbols with
:. These special characters make a big difference,
so make sure they’re correct.
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.
Jumping quickly between programs can be really confusing. In a normal development 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.
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 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.
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.
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 (http://api.rubyonrails.org/) 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, 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.
The following font conventions are used in this book:
Indicates pathnames, filenames, and program names; Internet addresses, such as domain names and URLs; and new items where they are defined.
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.
The code examples for this book, which are available from http://oreil.ly/LearningRails3, 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 chapter. 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 firstname.lastname@example.org.
Technology professionals, software developers, web designers, and business and creative 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 organizations, government agencies, and individuals. Subscribers have access to thousands 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.
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)|
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 http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Thanks to Mike Loukides for thinking that Rails could use a new and different approach, 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 http://railscasts.com/.
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.