Preface

Let me tell you why you’re here. You’re here because you know something. What you know you can’t explain, but you feel it. You’ve felt it your entire life: that there’s something wrong in the world. You don’t know what it is, but it’s there. Like a splinter in your mind, driving you mad. It is this feeling that brought you to me.

Morpheus, The Matrix

What is wrong in the world? Web development. It is way harder than it has to be.

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 the power of Rails 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 the many interlinked components of Rails.

Note

This updated version of Learning Rails covers version 5.0. There are substantial changes from earlier versions. Rails itself keeps changing, even in ways that affect beginners.

Who This Book Is For

If you’ve been working with the Web long enough, you’ll 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.)

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 hidden behind a graphical interface either. If you are not comfortable working from the command line this is a nice goal [as a web developer] to work toward. General fluency at the command line is a nice gateway drug to more sofisticated dev ops (development operations) and sys admin (system administrator) skills. While web development and dev ops are very different skill sets, I have never met a good web developer that did not know some dev ops, just as I have never met a good sys admin who did not have some development and coding skills.

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.

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 the ActiveRecord library in Rails 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’s 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 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.

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 Chapter 1, and then explore Appendix A 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:

  • Programming Ruby, Fourth Edition by Dave Thomas with Chad Fowler and Andy Hunt (Pragmatic Bookshelf, 2013)

  • The Well-Grounded Rubyist by David A. Black (Manning, 2014)

  • 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, 2015)

  • Practical Object-Oriented Design in Ruby: An Agile Primer by Sandi Metz (Addison-Wesley, 2012)

  • 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 the following:

  • For maximum excitement, try http://railsforzombies.com/, a training tool that includes video and exercises. The first few videos are free.

  • For the latest Ruby on Rails Screencasts, check out Go Rails.

  • While these videos are out of date (Rails 3), many are still very relevant. Try RailsCasts. Ryan Bates’s style has been the gold standard for technical screencasts for almost a decade.

  • For updates to this book, including screencasts, check out this book’s website.

  • The Ruby on Rails Tutorial by Michael Hartl provides a faster-moving introduction that covers many more extensions for Rails.

  • 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). The perpetual evolution of Rails 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, 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.

Rails Versions

The Rails team is perpetually improving Rails and releasing new versions. This book was updated for Rails 5.0 and Ruby 2.2.3.

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 2.2.3. Versions of Ruby older than 2.x may cause problems for Rails 5.x. Chapter 1 explores how to install Ruby, but you may need to find documentation specific to your 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 5.x, but Rails keeps changing in ways that break even simple code. The examples on http://bit.ly/learn-rails-5 were writen for Ruby 2.2.3 and Rails 5.0. If you’re running a version of Rails other than 5.0, 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 installations use MySQL or other databases. If you’re getting errors that have “sql” in them somewhere, it’s probably the database. All the examples in the this book use SQLite. This is installed with Rails, and usually does not require attention. Check 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 gems. 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.

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 conventions 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 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.

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.

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 at https://github.com/bbulpett/LR5.

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 this book’s O’Reilly page.

There’s also a link to errata on the O’Reilly site. 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.

Note

This icon signifies a tip, suggestion, or general note.

Warning

This icon indicates a warning or caution.

Using Code Examples

First let me thank Barnabas Bulpett for his work in creating the sample applications for this book. His tireless work and attention to 12 a.m. emails has ensured the compainion code for the book is flawless. Also, he has created a very helpful README.md at the root of each application that includes helpful tips on the functionality of each app.

The code examples for this book, which are available from http://oreil.ly/LearningRails5, 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.

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 5 by J. Mark Locklear, 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 permissions@oreilly.com.

O’Reilly Safari

Note

Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals.

Members have access to thousands of books, training videos, Learning Paths, interactive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, 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, and Course Technology, among others.

For more information, please visit http://oreilly.com/safari.

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 lectures, errata, examples, and any additional information. You can access this page at http://learningrails5.com.

In addition, O’Reilly maintains a page for the book at http://bit.ly/learn-rails-5.

To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com.

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

Acknowledgments

This book was updated to Rails 5 in May 2016. For this revision I would like to thank Barnabas Bulpett for his help, support, and motivation while updating and rewriting the book. Barnabas not only wrote all of the sample book code, but entirly rewrote Chapter 10, in addition to making significant content contributions throughout other chapters. A huge thanks to Natasha Ansari for updating all of the images in the book, in addition to editing and tech review, and thanks also to Aaron Sumner for tech review.

Mark Locklear would like to thank his wife Erica for showing him what true passion is, his daughter Faith for helping him appreciate the simple things in life, and his parents John Pat and Deletha for giving him the ultimate example of hard work and perseverance.

Barnabas Bulpett would like to thank O’Reilly Media and Mark Locklear for giving him the opportunity to provide the example code that accompanies this book. In addition, he wishes thank his two children, Kaya and Moses, for their support and patience through the late nights of work. Barnabas also thanks his father, Thomas Bulpett, for teaching him the value of hard work.

Natasha Ansari would like to thank Barnabas Bulpett for his dedication and hard work and Mark Locklear for showing us that Rails makes sense (kinda).

We’d also like to thank Simon St. Laurent, Edd Dumbill, and Eric J. Gruber for their work on the previous editions of the book.

Finally, thanks to Rachel Monaghan for cleaning up our prose, Nicole Shelby and Melanie Yarbrough for getting this book through production, and Judy McConville for the patient work it takes to build an index.

Get Learning Rails 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.