Ruby on Rails™ 3 Tutorial
Total Page:16
File Type:pdf, Size:1020Kb
Praise for Ruby on Rails™ 3 Tutorial RailsTutorial.org: Michael Hartl’s awesome new Rails Tutorial The Ruby on Rails ™ 3 Tutorial: Learn Rails by Example by Michael Hartl has become a must read for developers learning how to build Rails apps. —Peter Cooper, editor of Ruby Inside Very detailed and hands-on Rails Tutorial! Great job! I’m learning Rails, and found your tutorial to be one of the most detailed and hands-on guides. Besides many details of Rails, it also taught me about Git, Heroku, RSpec, Webrat, and most important (at least to me), it emphasized the Test-Driven Development (TDD) methodology. I learned a lot from your tutorial. Keep up the good job! Thanks so much for sharing it. —Albert Liu, senior manager, Achievo Corporation. Ruby on Rails Tutorial is the best! Just wanted to say that your Ruby on Rails tutorial is the best! I’ve been trying for a while to wrap my head around Rails. Going through your tutorial, I’m finally feeling comfortable in the Rails environment. Your pedagogical style of gradually introducing more complex topics while at the same time giving the reader the instant gratification and a sense of accomplishment with working examples really works for me. I also like the tips and suggestions that give me a sense of learning from a real Rails insider. Your e-mail response to a problem I ran into is an example of your generous sharing of your experience. —Ron Bingham, CEO, SounDBuytz I love the writing style of the Rails Tutorial I love the writing style of the Rails Tutorial, and there is so much content that is different from other Rails books out there, making it that much more valuable...Thanks for your work! —Allen Ding RUBY ON RAILS™ 3 TUTORIAL Addison-Wesley Professional Ruby Series Obie Fernandez, Series Editor Visit informit.com/ruby for a complete list of available products. he Addison-Wesley Professional Ruby Series provides readers T with practical, people-oriented, and in-depth information about applying the Ruby platform to create dynamic technology solutions. The series is based on the premise thatthe need for expert reference books, written by experienced practitioners, will never be satisfied solely by blogs and the Internet. RUBY ON RAILS™ 3 TUTORIAL Learn Rails™ by Example Michael Hartl Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City Many of the designations used by manufacturers and sellers to distinguish their products are claimed Editor-in-Chief as trademarks. Where those designations appear in this book, and the publisher was aware of a Mark Taub trademark claim, the designations have been printed with initial capital letters or in all capitals. Executive Acquisitions Editor Debra Williams Cauley The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is Managing Editor assumed for incidental or consequential damages in connection with or arising out of the use of the John Fuller information or programs contained herein. Project Editor Elizabeth Ryan The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to Copy Editor your business, training goals, marketing focus, and branding interests. For more information, please Erica Orloff contact: Indexer Claire Splan U.S. Corporate and Government Sales (800) 382-3419 Proofreader [email protected] Claire Splan For sales outside the United States please contact: Publishing Coordinator International Sales Kim Boedigheimer [email protected] Cover Designer Gary Adair Visit us on the Web: informit.com/aw Compositor Library of Congress Cataloging-in-Publication Data Glyph International Hartl, Michael. Ruby on rails 3 tutorial : learn Rails by example / Michael Hartl. p. cm. Includes index. ISBN-10: 0-321-74312-1 (pbk. : alk. paper) ISBN-13: 978-0-321-74312-1 (pbk. : alk. paper) 1. Ruby on rails (Electronic resource) 2. Web site development. 3. Ruby (Computer program language) I. Title. TK5105.8885.R83H37 2011 005.1 17–dc22 2010039450 Copyright © 2011 Michael Hartl All rights reserved. Printed in the United States of America. This publication is protected by copyright, 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. For information regarding permissions, write to: Pearson Education, Inc. Rights and Contracts Department 501 Boylston Street, Suite 900 Boston, MA 02116 Fax: (617) 671-3447 The source code in Ruby on Rails ™ 3 Tutorial is released under the MIT License. ISBN 13: 978-0-321-74312-1 ISBN 10: 0-321-74312-1 Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor, Michigan First printing, December 2010 Contents Foreword by Derek Sivers xv Foreword by Obie Fernandez xvii Acknowledgments xix About the Author xxi Chapter 1 From Zero to Deploy 1 1.1 Introduction 3 1.1.1 Comments for Various Readers 4 1.1.2 “Scaling” Rails 7 1.1.3 Conventions in This Book 7 1.2 Up and Running 9 1.2.1 Development Environments 9 1.2.2 Ruby, RubyGems, Rails, and Git 11 1.2.3 The First Application 15 1.2.4 Bundler 16 1.2.5 rails server 20 1.2.6 Model-View-Controller (MVC) 22 1.3 Version Control with Git 24 1.3.1 Installation and Setup 24 1.3.2 Adding and Committing 26 1.3.3 What Good Does Git Do You? 28 1.3.4 GitHub 29 1.3.5 Branch, Edit, Commit, Merge 31 vii viii Contents 1.4 Deploying 35 1.4.1 Heroku Setup 36 1.4.2 Heroku Deployment, Step One 37 1.4.3 Heroku Deployment, Step Two 37 1.4.4 Heroku Commands 39 1.5 Conclusion 40 Chapter 2 A Demo App 41 2.1 Planning the Application 41 2.1.1 Modeling Users 43 2.1.2 Modeling Microposts 44 2.2 The Users Resource 44 2.2.1 A User Tour 46 2.2.2 MVC in Action 49 2.2.3 Weaknesses of This Users Resource 58 2.3 The Microposts Resource 58 2.3.1 A Micropost Microtour 58 2.3.2 Putting the micro in Microposts 61 2.3.3 A User has_many Microposts 63 2.3.4 Inheritance Hierarchies 66 2.3.5 Deploying the Demo App 68 2.4 Conclusion 69 Chapter 3 Mostly Static Pages 71 3.1 Static Pages 74 3.1.1 Truly Static Pages 75 3.1.2 Static Pages with Rails 78 3.2 Our First Tests 84 3.2.1 Testing Tools 84 3.2.2 TDD: Red, Green, Refactor 86 3.3 Slightly Dynamic Pages 103 3.3.1 Testing a Title Change 103 3.3.2 Passing Title Tests 106 3.3.3 Instance Variables and Embedded Ruby 108 3.3.4 Eliminating Duplication with Layouts 112 3.4 Conclusion 115 3.5 Exercises 116 Contents ix Chapter 4 Rails-Flavored Ruby 119 4.1 Motivation 119 4.1.1 A title Helper 119 4.1.2 Cascading Style Sheets 122 4.2 Strings and Methods 125 4.2.1 Comments 125 4.2.2 Strings 126 4.2.3 Objects and Message Passing 129 4.2.4 Method Definitions 132 4.2.5 Back to the title Helper 133 4.3 Other Data Structures 134 4.3.1 Arrays and Ranges 134 4.3.2 Blocks 137 4.3.3 Hashes and Symbols 139 4.3.4 CSS Revisited 142 4.4 Ruby Classes 144 4.4.1 Constructors 144 4.4.2 Class Inheritance 145 4.4.3 Modifying Built-In Classes 148 4.4.4 A Controller Class 150 4.4.5 A User Class 152 4.5 Exercises 154 Chapter 5 Filling in the Layout 157 5.1 Adding Some Structure 157 5.1.1 Site Navigation 159 5.1.2 Custom CSS 164 5.1.3 Partials 171 5.2 Layout Links 177 5.2.1 Integration Tests 178 5.2.2 Rails Routes 181 5.2.3 Named Routes 183 5.3 User Signup: A First Step 186 5.3.1 Users Controller 186 5.3.2 Signup URL 188 5.4 Conclusion 191 5.5 Exercises 191 x Contents Chapter 6 Modeling and Viewing Users, Part I 193 6.1 User Model 194 6.1.1 Database Migrations 196 6.1.2 The Model File 201 6.1.3 Creating User Objects 203 6.1.4 Finding User Objects 207 6.1.5 Updating User Objects 208 6.2 User Validations 210 6.2.1 Validating Presence 210 6.2.2 Length Validation 217 6.2.3 Format Validation 218 6.2.4 Uniqueness Validation 222 6.3 Viewing Users 227 6.3.1 Debug and Rails Environments 227 6.3.2 User Model, View, Controller 230 6.3.3 A Users Resource 232 6.4 Conclusion 236 6.5 Exercises 237 Chapter 7 Modeling and Viewing Users, Part II 239 7.1 Insecure Passwords 239 7.1.1 Password Validations 240 7.1.2 A Password Migration 244 7.1.3 An Active Record Callback 247 7.2 Secure Passwords 250 7.2.1 A Secure Password Test 251 7.2.2 Some Secure Password Theory 252 7.2.3 Implementing has_password? 254 7.2.4 An Authenticate Method 258 7.3 Better User Views 262 7.3.1 Testing the User Show Page (With Factories) 263 7.3.2 A Name and A Gravatar 268 7.3.3 A User Sidebar 276 7.4 Conclusion 279 7.4.1 Git Commit 279 7.4.2 Heroku Deploy 280 7.5 Exercises 280 Contents xi Chapter 8 Sign Up 283 8.1 Signup Form 283 8.1.1 Using form_for 286 8.1.2 The Form HTML 288 8.2 Signup Failure 292 8.2.1 Testing Failure 292 8.2.2 A Working Form 295 8.2.3 Signup Error Messages 299 8.2.4 Filtering Parameter Logging 303 8.3 Signup Success 305 8.3.1 Testing Success 305 8.3.2 The Finished Signup Form 308 8.3.3 The Flash 308 8.3.4 The First Signup 312 8.4 RSpec Integration Tests 313 8.4.1 Integration Tests with Style 315 8.4.2 Users Signup Failure Should not Make a New User 315 8.4.3 Users Signup Success Should Make a New User 319 8.5 Conclusion 321 8.6 Exercises 321 Chapter 9 Sign In, Sign Out 325 9.1 Sessions 325 9.1.1 Sessions Controller 326 9.1.2 Signin Form 328 9.2 Signin Failure 332 9.2.1 Reviewing form Submission 333 9.2.2