Ruby On Rails Tutorial: Learn Web Developments With Rails - GUTL

Transcription

www.it-ebooks.info

Praise for Michael Hartl’sBooks and Videoson Ruby on RailsTM‘‘My former company (CD Baby) was one of the first to loudly switch to Ruby onRails, and then even more loudly switch back to PHP (Google me to read about thedrama). This book by Michael Hartl came so highly recommended that I had to tryit, and the Ruby on Rails TM Tutorial is what I used to switch back to Rails again.’’—From the Foreword by Derek Sivers (sivers.org)Formerly: Founder, CD BabyCurrently: Founder, Thoughts Ltd.‘‘Michael Hartl’s Rails Tutorial book is the #1 (and only, in my opinion) place tostart when it comes to books about learning Rails. . . . It’s an amazing piece of workand, unusually, walks you through building a Rails app from start to finish withtesting. If you want to read just one book and feel like a Rails master by the end ofit, pick the Ruby on Rails TM Tutorial .’’—Peter CooperEditor, Ruby Insidewww.it-ebooks.info

‘‘Grounded in the real world.’’—I Programmer (www.i-programmer.info), by Ian Elliot‘‘The book gives you the theory and practice, while the videos focus on showing youin person how its done. Highly recommended combo.’’—Antonio Cangiano, Software Engineer, IBM‘‘The author is clearly an expert at the Ruby language and the Rails framework, butmore than that, he is a working software engineer who introduces best practicesthroughout the text.’’—Greg Charles, Senior Software Developer, Fairway Technologies‘‘Overall, these video tutorials should be a great resource for anyone new to Rails.’’—Michael Morin, ruby.about.com‘‘Hands-down, I would recommend this book to anyone wanting to get into Rubyon Rails development.’’—Michael Crump, Microsoft MVPwww.it-ebooks.info

RUBY ON RAILS TUTORIALTMSecond Editionwww.it-ebooks.info

Visit informit.com/ruby for a complete list of available products.IThe Addison-Wesley Professional Ruby Series provides readerswith practical, people-oriented, and in-depth information aboutapplying the Ruby platform to create dynamic technology solutions.The series is based on the premise that the need for expert referencebooks, written by experienced practitioners, will never be satisfied solelyby blogs and the Internet.www.it-ebooks.info

RUBY ON RAILS TUTORIALTMLearn Web Developments with RailsSecond EditionMichael HartlUpper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCapetown Sydney Tokyo Singapore Mexico Citywww.it-ebooks.info

Many of the designations used by manufacturers and sellers to distinguish their products are claimedas trademarks. Where those designations appear in this book, and the publisher was aware of atrademark claim, the designations have been printed with initial capital letters or in all capitals.The author and publisher have taken care in the preparation of this book, but make no expressed orimplied warranty of any kind and assume no responsibility for errors or omissions. No liability isassumed for incidental or consequential damages in connection with or arising out of the use of theinformation or programs contained herein.The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases orspecial sales, which may include electronic versions and/or custom covers and content particular toyour business, training goals, marketing focus, and branding interests. For more information, pleasecontact:Editor-in-ChiefMark TaubExecutive EditorDebra Williams CauleyManaging EditorJohn FullerFull-Service ProductionManagerJulie B. NahilProject ManagerLaserwordsCopy EditorLaserwordsU.S. Corporate and Government Sales(800) wordsFor sales outside the United States please contact:International sReviewerJennifer LindnerVisit us on the Web: informit.com/awCataloging-in-Publication Data is on file with the Library of Congress.Copyright 2013 Michael HartlAll rights reserved. Printed in the United States of America. This publication is protected bycopyright, and permission must be obtained from the publisher prior to any prohibited reproduction,storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,photocopying, recording, or likewise. To obtain permission to use material from this work, pleasesubmit a written request to Pearson Education, Inc., Permissions Department, One Lake Street,Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236-3290.The source code in Ruby on Rails TM Tutorial is released under the MIT License.ISBN 13: 978-0-321-83205-4ISBN 10:0-321-83205-1Text printed in the United States on recycled paper at Edwards Brothers Malloy in Ann Arbor,Michigan.First printing, July 2012www.it-ebooks.infoPublishing CoordinatorKim BoedigheimerCover DesignerChuti PrasertsithCompositorLaserwords

ContentsForeword to the First Edition by Derek Sivers xvForeword to the First Edition by Obie Fernandez xviiAcknowledgments xixAbout the Author xxiChapter 11.11.21.3From Zero to Deploy 1Introduction 31.1.1Comments for Various Readers 41.1.2‘‘Scaling’’ Rails 71.1.3Conventions in This Book 7Up and Running 91.2.1Development Environments 101.2.2Ruby, RubyGems, Rails, and Git 121.2.3The First Application 171.2.4Bundler 191.2.5rails server 231.2.6Model-view-controller (MVC) 25Version Control with Git 271.3.1Installation and Setup 271.3.2Adding and Committing 301.3.3What Good Does Git Do You? 31viiwww.it-ebooks.info

Contentsviii1.41.51.3.4GitHub 321.3.5Branch, Edit, Commit, Merge 34Deploying 391.4.1Heroku Setup 391.4.2Heroku Deployment, Step One 401.4.3Heroku Deployment, Step Two 401.4.4Heroku Commands 41Conclusion 43Chapter 22.12.22.32.4Planning the Application 452.1.1Modeling Demo Users 472.1.2Modeling Demo Microposts 48The Users Resource 492.2.1A User Tour 512.2.2MVC in Action 562.2.3Weaknesses of this Users Resource 62The Microposts Resource 632.3.1A Micropost Microtour 632.3.2Putting the micro in Microposts 662.3.3A User has many Microposts 682.3.4Inheritance Hierarchies 702.3.5Deploying the Demo App 73Conclusion 74Chapter 33.13.23.33.4A Demo App 45Mostly Static Pages 77Static Pages 823.1.1Truly Static Pages 823.1.2Static Pages with Rails 85Our First Tests 933.2.1Test-driven Development 933.2.2Adding a Page 99Slightly Dynamic Pages 1033.3.1Testing a Title Change 1033.3.2Passing Title Tests 1063.3.3Embedded Ruby 1083.3.4Eliminating Duplication with LayoutsConclusion 114www.it-ebooks.info111

Contents3.53.6ixExercises 114Advanced Setup 1173.6.1Eliminating bundle exec 1183.6.2Automated Tests with Guard 1203.6.3Speeding up Tests with Spork 1233.6.4Tests inside Sublime Text 127Chapter 44.14.24.34.44.54.6Motivation 129Strings and Methods 1344.2.1Comments 1344.2.2Strings 1354.2.3Objects and Message Passing 1384.2.4Method Definitions 1414.2.5Back to the Title Helper 142Other Data Structures 1424.3.1Arrays and Ranges 1424.3.2Blocks 1464.3.3Hashes and Symbols 1484.3.4CSS revisited 152Ruby Classes 1534.4.1Constructors 1534.4.2Class Inheritance 1554.4.3Modifying Built-in Classes 1584.4.4A Controller Class 1594.4.5A User Class 161Conclusion 164Exercises 164Chapter 55.15.2Rails-Flavored Ruby 129Filling in the Layout 167Adding Some Structure 1675.1.1Site Navigation 1695.1.2Bootstrap and Custom CSS 1755.1.3Partials 181Sass and the Asset Pipeline 1875.2.1The Asset Pipeline 1875.2.2Syntactically Awesome Stylesheets 190www.it-ebooks.info

Contentsx5.35.45.55.6Layout Links 1975.3.1Route Tests 2005.3.2Rails Routes 2025.3.3Named Routes 2055.3.4Pretty RSpec 207User Signup: A First Step 2115.4.1Users Controller 2125.4.2Signup URI 213Conclusion 215Exercises 217Chapter 66.16.26.36.46.5User Model 2226.1.1Database Migrations 2236.1.2The Model File 2286.1.3Creating User Objects 2306.1.4Finding User Objects 2336.1.5Updating User Objects 235User Validations 2366.2.1Initial User Tests 2366.2.2Validating Presence 2396.2.3Length Validation 2436.2.4Format Validation 2456.2.5Uniqueness Validation 249Adding a Secure Password 2546.3.1An Encrypted Password 2556.3.2Password and Confirmation 2576.3.3User Authentication 2606.3.4User Has Secure Password 2636.3.5Creating a User 265Conclusion 267Exercises 268Chapter 77.1Modeling Users 221Sign Up 271Showing Users 2717.1.1Debug and Rails Environments7.1.2A Users Resource 278272www.it-ebooks.info

Contents7.27.37.47.57.6xi7.1.3Testing the User Show Page (with Factories)7.1.4A Gravatar Image and a Sidebar 286Signup Form 2927.2.1Tests for User Signup 2937.2.2Using form for 2977.2.3The Form HTML 301Signup Failure 3037.3.1A Working Form 3037.3.2Signup Error Messages 308Signup Success 3127.4.1The Finished Signup Form 3137.4.2The Flash 3157.4.3The First Signup 3177.4.4Deploying to Production with SSL 317Conclusion 321Exercises 321Chapter 88.18.28.38.48.5Sign In, Sign Out 325Sessions and Signin Failure 3258.1.1Sessions Controller 3268.1.2Signin Tests 3308.1.3Signin Form 3338.1.4Reviewing Form Submission 3368.1.5Rendering with a Flash Message 339Signin Success 3438.2.1Remember Me 3438.2.2A Working sign in Method 3498.2.3Current User 3518.2.4Changing the Layout Links 3558.2.5Signin upon Signup 3598.2.6Signing Out 361Introduction to Cucumber (Optional) 3638.3.1Installation and Setup 3648.3.2Features and Steps 3658.3.3Counterpoint: RSpec Custom MatchersConclusion 371Exercises 372www.it-ebooks.info368282

ContentsxiiChapter 99.19.29.39.49.59.6Updating Users 3739.1.1Edit Form 3749.1.2Unsuccessful Edits 3809.1.3Successful Edits 382Authorization 3859.2.1Requiring Signed-in Users 3869.2.2Requiring the Right User 3909.2.3Friendly Forwarding 392Showing All Users 3969.3.1User Index 3969.3.2Sample Users 4039.3.3Pagination 4049.3.4Partial Refactoring 410Deleting Users 4139.4.1Administrative Users 4139.4.2The destroy Action 417Conclusion 422Exercises 424Chapter 1010.110.210.310.410.5Updating, Showing, and Deleting Users 373User Microposts 429A Micropost Model 42910.1.1 The Basic Model 43010.1.2 Accessible Attributes and the First Validation10.1.3 User/Micropost Associations 43310.1.4 Micropost Refinements 43910.1.5 Content Validations 443Showing Microposts 44510.2.1 Augmenting the User Show Page 44610.2.2 Sample Microposts 450Manipulating Microposts 45410.3.1 Access Control 45610.3.2 Creating Microposts 45910.3.3 A Proto-feed 46710.3.4 Destroying Microposts 475Conclusion 479Exercises 480www.it-ebooks.info432

ContentsxiiiChapter 1111.111.211.311.411.5IndexFollowing Users 483The Relationship Model 48411.1.1 A Problem with the Data Model (and a Solution) 48511.1.2 User/Relationship Associations 49111.1.3 Validations 49511.1.4 Followed users 49511.1.5 Followers 500A Web Interface for Following Users 50311.2.1 Sample Following Data 50311.2.2 Stats and a Follow Form 50511.2.3 Following and Followers Pages 51511.2.4 A Working Follow Button the Standard Way 51911.2.5 A Working Follow Button with Ajax 524The Status Feed 52911.3.1 Motivation and Strategy 53011.3.2 A First Feed Implementation 53211.3.3 Subselects 53511.3.4 The New Status Feed 538Conclusion 53911.4.1 Extensions to the Sample Application 54011.4.2 Guide to Further Resources 542Exercises 543545www.it-ebooks.info

This page intentionally left blankwww.it-ebooks.info

Foreword to the First EditionMy former company (CD Baby) was one of the first to loudly switch to Ruby on Rails,and then even more loudly switch back to PHP (Google me to read about the drama).This book by Michael Hartl came so highly recommended that I had to try it, andRuby on Rails TM 3 Tutorial is what I used to switch back to Rails again.Though I’ve worked my way through many Rails books, this is the one that finallymade me get it. Everything is done very much ‘‘the Rails way’’—a way that felt veryunnatural to me before, but now after doing this book finally feels natural. This is alsothe only Rails book that does test-driven development the entire time, an approachhighly recommended by the experts but which has never been so clearly demonstratedbefore. Finally, by including Git, GitHub, and Heroku in the demo examples, theauthor really gives you a feel for what it’s like to do a real-world project. The tutorial’scode examples are not in isolation.The linear narrative is such a great format. Personally, I powered through the RailsTutorial in three long days, doing all the examples and challenges at the end of eachchapter. Do it from start to finish, without jumping around, and you’ll get the ultimatebenefit.Enjoy!—Derek Sivers (sivers.org)Formerly: Founder, CD BabyCurrently: Founder, Thoughts Ltd.xvwww.it-ebooks.info

This page intentionally left blankwww.it-ebooks.info

Foreword to the First Edition‘‘If you want to learn web development with Ruby on Rails, how should I start?’’ Foryears Michael Hartl has provided the answer as author of the RailsSpace tutorial in ourseries and now the new Ruby on Rails TM 3 Tutorial that you hold in your hands (or PDFreader, I guess).I’m so proud of having Michael on the series roster. He is living, breathing proofthat us Rails folks are some of the luckiest in the wide world of technology. Beforegetting into Ruby, Michael taught theoretical and computational physics at Caltech forsix years, where he received the Lifetime Achievement Award for Excellence in Teachingin 2000. He is a Harvard graduate, has a Ph.D. in Physics from Caltech, and is analumnus of Paul Graham’s esteemed Y Combinator program for entrepreneurs. Andwhat does Michael apply his impressive experience and teaching prowess to? Teachingnew software developers all around the world how to use Ruby on Rails effectively!Lucky we are indeed!The availability of this tutorial actually comes at a critical time for Rails adoption.We’re five years into the history of Rails and today’s version of the platform hasunprecedented power and flexibility. Experienced Rails folks can leverage that powereffectively, but we’re hearing growing cries of frustration from newcomers. The amountof information out there about Rails is fantastic if you know what you’re doingalready. However, if you’re new, the scope and mass of information about Rails can bemind-boggling.Luckily, Michael takes the same approach as his first book in the series, buildinga sample application from scratch, and writes in a style that’s meant to be read fromstart to finish. Along the way, he explains all the little details that are likely to trip upxviiwww.it-ebooks.info

Foreword to the First Editionxviiibeginners. Impressively, he goes beyond just a straightforward explanation of what Railsdoes and ventures into prescriptive advice about good software development practices,such as test-driven development. Neither does Michael constrain himself to a boxdelineated by the extents of the Rails framework—he goes ahead and teaches the readerto use tools essential to existence in the Rails community, such as Git and GitHub.In a friendly style, he even provides copious contextual footnotes of benefit to newprogrammers, such as the pronunciation of SQL and pointers to the origins of loremipsum. Tying all the content together in a way that remains concise and usable is truly atour de force of dedication!I tell you with all my heart that this book is one of the most significant titles inmy Professional Ruby Series, because it facilitates the continued growth of the Railsecosystem. By helping newcomers become productive members of the communityquickly, he ensures that Ruby on Rails continues its powerful and disruptive charge intothe mainstream. The Rails Tutorial is potent fuel for the fire that is powering growthand riches for so many of us, and for that we are forever grateful.—Obie Fernandez, Series Editorwww.it-ebooks.info

AcknowledgmentsThe Ruby on Rails TM Tutorial owes a lot to my previous Rails book, RailsSpace, andhence to my coauthor Aurelius Prochazka. I’d like to thank Aure both for the work hedid on that book and for his support of this one. I’d also like to thank Debra WilliamsCauley, my editor on both RailsSpace and the Ruby on Rails TM Tutorial ; as long as shekeeps taking me to baseball games, I’ll keep writing books for her.I’d like to acknowledge a long list of Rubyists who have taught and inspired meover the years: David Heinemeier Hansson, Yehuda Katz, Carl Lerche, Jeremy Kemper,Xavier Noria, Ryan Bates, Geoffrey Grosenbach, Peter Cooper, Matt Aimonetti, GreggPollack, Wayne E. Seguin, Amy Hoy, Dave Chelimsky, Pat Maddox, Tom PrestonWerner, Chris Wanstrath, Chad Fowler, Josh Susser, Obie Fernandez, Ian McFarland,Steven Bristol, Wolfram Arnold, Alex Chaffee, Giles Bowkett, Evan Dorn, LongNguyen, James Lindenbaum, Adam Wiggins, Tikhon Bernstam, Ron Evans, WyattGreene, Miles Forrest, the good people at Pivotal Labs, the Heroku gang, the thoughtbotguys, and the GitHub crew. Thanks to Jen Lindner, Patty Donovan (Laserwords), andJulie Nahil and Michael Thurston from Pearson for their help with the book. Finally,many, many readers—far too many to list—have contributed a huge number of bugreports and suggestions during the writing of this book, and I gratefully acknowledgetheir help in making it as good as it can be.xixwww.it-ebooks.info

This page intentionally left blankwww.it-ebooks.info

About the AuthorMichael Hartl is the author of the Ruby on Rails TM Tutorial , the leading introductionto web development with Ruby on Rails. His prior experience includes writing anddeveloping RailsSpace, an extremely obsolete Rails tutorial book, and developing Insoshi,a once-popular and now-obsolete social networking platform in Ruby on Rails. In 2011,Michael received a Ruby Hero Award for his contributions to the Ruby community.He is a graduate of Harvard College, has a Ph.D. in physics from Caltech, and is analumnus of the Y Combinator entrepreneur program.xxiwww.it-ebooks.info

This page intentionally left blankwww.it-ebooks.info

1From Zero to DeployC HAPTERWelcome to Ruby on Rails Tutorial . The goal of this book is to be the best answer to thequestion, ‘‘If I want to learn web development with Ruby on Rails, where should I start?’’By the time you finish the Rails Tutorial, you will have all the skills you need to developand deploy your own custom web applications with Rails. You will also be ready to benefitfrom the many more advanced books, blogs, and screencasts that are part of the thrivingRails educational ecosystem. Finally, since the Rails Tutorial uses Rails 3, the knowledgeyou gain here represents the state of the art in web development. (The most up-to-dateversion of the Rails Tutorial can be found on the book’s website at http://railstutorial.org;if you are reading this book offline, be sure to check the online version of the RailsTutorial book at http://railstutorial.org/book for the latest updates.)Note that the goal of this book is not merely to teach Rails, but rather to teachweb development with Rails, which means acquiring (or expanding) the skills needed todevelop software for the World Wide Web. In addition to Ruby on Rails, this skillsetincludes HTML and CSS, databases, version control, testing, and deployment. Toaccomplish this goal, Rails Tutorial takes an integrated approach: You will learn Railsby example by building a substantial sample application from scratch. As Derek Siversnotes in the foreword, this book is structured as a linear narrative, designed to be readfrom start to finish. If you are used to skipping around in technical books, taking thislinear approach might require some adjustment, but I suggest giving it a try. You canthink of the Rails Tutorial as a video game where you are the main character and whereyou level up as a Rails developer in each chapter. (The exercises are the minibosses.)1www.it-ebooks.info

Chapter 1: From Zero to Deploy2In this first chapter, we’ll get started with Ruby on Rails by installing all the necessarysoftware and by setting up our development environment (Section 1.2). We’ll thencreate our first Rails application, called (appropriately enough) first app. The RailsTutorial emphasizes good software development practices, so immediately after creatingour fresh new Rails project we’ll put it under version control with Git (Section 1.3).And, believe it or not, in this chapter we’ll even put our first app on the wider web bydeploying it to production (Section 1.4).In Chapter 2, we’ll make a second project, whose purpose is to demonstrate thebasic workings of a Rails application. To get up and running quickly, we’ll build thisdemo app (called demo app) using scaffolding (Box 1.1) to generate code; since thiscode is both ugly and complex, Chapter 2 will focus on interacting with the demo appthrough its URIs (sometimes called URLs)1 using a web browser.The rest of the tutorial focuses on developing a single large sample application (calledsample app), writing all the code from scratch. We’ll develop the sample app usingtest-driven development (TDD), getting started in Chapter 3 by creating static pagesand then adding a little dynamic content. We’ll take a quick detour in Chapter 4 tolearn a little about the Ruby language underlying Rails. Then, in Chapter 5 throughChapter 9, we’ll complete the foundation for the sample application by making a sitelayout, a user data model, and a full registration and authentication system. Finally,in Chapter 10 and Chapter 11 we’ll add microblogging and social features to make aworking example site.The final sample application will bear more than a passing resemblance to a certainpopular social microblogging site—a site that, coincidentally, was also originally writtenin Rails. Although of necessity our efforts will focus on this specific sample application,the emphasis throughout the Rails Tutorial will be on general principles, so that you willhave a solid foundation no matter what kinds of web applications you want to build.Box 1.1 Scaffolding: Quicker, Easier, More SeductiveFrom the beginning, Rails has benefited from a palpable sense of excitement,starting with the famous 15-minute weblog video by Rails creator David HeinemeierHansson. That video and its successors are a great way to get a taste of Rails’ power,1. URI stands for Uniform Resource Identifier, while the slightly less general URL stands for Uniform ResourceLocator. In practice, the URI is usually equivalent to ‘‘the thing you see in the address bar of your browser.’’www.it-ebooks.info

1.1Introduction3and I recommend watching them. But be warned: They accomplish their amazing15-minute feat using a feature called scaffolding, which relies heavily on generatedcode, magically created by the Rails generate command.When writing a Ruby on Rails tutorial, it is tempting to rely on the scaffoldingapproach—it’s quicker, easier, more seductive. But the complexity and sheer amountof code in the scaffolding can be utterly overwhelming to a beginning Rails developer;you may be able to use it, but you probably won’t understand it. Following thescaffolding approach risks turning you into a virtuoso script generator with little (andbrittle) actual knowledge of Rails.In the Rails Tutorial, we’ll take the (nearly) polar opposite approach: AlthoughChapter 2 will develop a small demo app using scaffolding, the core of the RailsTutorial is the sample app, which we’ll start writing in Chapter 3. At each stage ofdeveloping the sample application, we will write small, bite-sized pieces of code—simple enough to understand, yet novel enough to be challenging. The cumulative effectwill be a deeper, more flexible knowledge of Rails, giving you a good backgroundfor writing nearly any type of web application.1.1 IntroductionSince its debut in 2004, Ruby on Rails has rapidly become one of the most powerfuland popular frameworks for building dynamic web applications. Everyone from scrappystartups to huge companies have used Rails: 37signals, GitHub, Shopify, Scribd, Twitter,LivingSocial, Groupon, Hulu, the Yellow Pages—the list of sites using Rails goes onand on. There are also many web development shops that specialize in Rails, suchas ENTP, thoughtbot, Pivotal Labs, and Hashrocket, plus innumerable independentconsultants, trainers, and contractors.What makes Rails so great? First of all, Ruby on Rails is 100 percent open-source,available under the permissive MIT License, and as a result it also costs nothing todownload or use. Rails also owes much of its success to its elegant and compact design;by exploiting the malleability of the underlying Ruby language, Rails effectively createsa domain-specific language for writing web applications. As a result, many commonweb programming tasks—such as generating HTML, making data models, and routingURIs—are easy with Rails, and the resulting application code is concise and readable.Rails also adapts rapidly to new developments in web technology and frameworkdesign. For example, Rails was one of the first frameworks to fully digest and implementthe REST architectural style for structuring web applications (which we’ll be learningwww.it-ebooks.info

Chapter 1: From Zero to Deploy4about throughout this tutorial). And when other frameworks develop successful newtechniques, Rails creator David Heinemeier Hansson and the Rails core team don’thesitate to incorporate their ideas. Perhaps the most dramatic example is the merger ofRails and Merb, a rival Ruby web framework, so that Rails now benefits from Merb’smodular design, stable API, and improved performance.Finally, Rails benefits from an unusually enthusiastic and diverse community. Theresults include hundreds of open-source contributors, well-attended conferences, a hugenumber of plugins and gems (self-contained solutions to specific problems such aspagination and image upload), a rich variety of informative blogs, and a cornucopiaof discussion forums and IRC channels. The large number of Rails programmers alsomakes it easier to handle the inevitable application errors: The ‘‘Google the errormessage’’ algorithm nearly always produces a relevant blog post or discussion-forumthread.1.1.1 Comments for Various ReadersThe Rails Tutorial contains integrated tutorials not only for Rails, but also for theunderlying Ruby language, the RSpec testing framework, HTML, CSS, a small amountof JavaScript, and even a little SQL. This means that, no matter where you currentlyare in your knowledge of web development, by the time you finish this tutorial youwill be ready for more advanced Rails resources, as well as for the more systematictreatments of the other subjects mentioned. It also means that there’s a lot of materialto cover; if you don’t already have experience programming computers, you might findit overwhelming. The comments below contain some suggestions for approaching theRails Tutorial depending on your background.All readers: One common question when learning Rails is whether to learn Rubyfirst. The answer depends on your personal learning style and how much programmingexperience you already have. If you prefer to learn everything systematically from theground up, or if you have never programmed before, then learning Ruby first mightwork well for you, and in this case I recommend Beginning Ruby by Peter Cooper.On the other hand, many beginning Rails developers are excited about making webapplications, and would rather not slog through a 500-page book on pure Ruby beforeever writing a single web page. In this case, I recommend following the short interactivewww.it-ebooks.info

1.1Introduction5tutorial at TryRuby,2 and then optimally do the free tutorial at Rails for Zombies 3 toget a taste of what Rails can do.Another common question is whether to use tests from the start. As noted inthe introduction, the Rails Tutorial uses test-driven development (also called test-firstdevelopment), which in my view is the best way to develop Rails applications, but itdoes introduce a substantial amount of overhead and complexity. If you find yourselfgetting bogged down by the tests, I suggest either skipping them on a first reading or(even better) using them as a tool to verify your code’s correctness without worryingabout how they work. This latter strategy involves creating the necessary test files (calledspecs) and filling them with the test code exactly as it appears in the book. You can thenrun the test suite (as described in Chapter 5) to watch it fail, then write the applicationcode as described in the tutorial, and finally re-run the test suite to watch it pass.Inexperienced programmers: The Rails Tutorial is not aimed principally at beginningprogrammers, and web applications, even relatively simple ones, are by their naturefairly complex. If you are completely new to web programming and find the RailsTutorial too difficult, I suggest learning the basics of HTML and CSS and thengiving the Rails Tutorial another go. (Unfortunately, I don’t have a personal recommendation here, but Head First HTML looks promising, and one reader recommendsCSS: The Missing Manual by David Sawyer McFarland.) You might also consider reading the first few chapters of Beginning Ruby by Peter Cooper, which starts with sampleapplications much smaller than a full-blown web app. That said, a surprising numberof beginners have used this tutorial to learn web development, so I suggest giving ita try, and I especially recommend the Rails Tutorial screencast series4 to give you an‘‘over-the-shoulder’’ look at Rails software development.Experienced programmers new to web development: Your previous experience meansyou probably already understand ideas like classes, methods, data structures, and others,which is a big advantage. Be warned that if your background is in C/C or Java, you2. http://tryruby.org3. http://railsforzombies.org4. info

Chapter 1: From Zero to Deploy6may find Ruby a bit of an odd duck, and it might take time to get used to it; just stickwith it and eventually you’ll be fine. (Ruby even lets you put semicolons at

it, and the Ruby on RailsTM Tutorial is what I used to switch back to Rails again. —From the Foreword by Derek Sivers (sivers.org) Formerly: Founder, CD Baby Currently: Founder, Thoughts Ltd. ''Michael Hartls Rails Tutorial book is the #1 (and only, in my opinion) place to start when it comes to books about learning Rails. . . .