T R W HE AILS AY Obie Fernandez 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 as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark 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 or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential dam- ages in connection with or arising out of the use of the information or programs contained herein. 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 your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382-3419 [email protected] For sales outside the United States please contact: International Sales [email protected] This Book Is Safari Enabled The Safari® Enabled icon on the cover of your favorite technology book means the book is available through Safari Bookshelf. When you buy this book, you get free access to the online edition for 45 days. Safari Bookshelf is an electronic reference library that lets you easily search thousands of technical books, find code sam- ples, download chapters, and access technical information whenever and wherever you need it. To gain 45-day Safari Enabled access to this book: • Go to http://www.awprofessional.com/safarienabled • Complete the brief registration form • Enter the coupon code 52GH-T7VF-4T1U-ATFQ-DMJH If you have difficulty registering on Safari Bookshelf or accessing the online edition, please e-mail [email protected]. Visit us on the Web: www.awprofessional.com Library of Congress Cataloging-in-Publication Data: Fernandez, Obie. The Rails way / Obie Fernandez. p. cm. Includes index. ISBN 0-321-44561-9 (pbk. : alk. paper) 1. Ruby on rails (Electronic resource) 2. Object-oriented programming (Computer science) 3. Ruby (Computer pro- gram language) 4. Web site development . 5. Application softare--Development. I. Title. QA76.64F47 2007 005.1'17--dc22 2007039880 Copyright © 2008 Pearson Education, Inc. 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 permis- sions, write to: Pearson Education, Inc. Rights and Contracts Department 75 Arlington Street, Suite 300 Boston, MA 02116 Fax: (617) 848-7047 This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/). ISBN-13: 978-0-321-44561-9 ISBN-10: 0-321-44561-9 Text printed in the United States on recycled paper at R.R. Donnelly in Crawfordsville, IN. First printing November 2007 Parts of this book contain material excerpted from the Ruby and Rails source code and API documentation, Copyright © 2004-2006 by David Heinemeier Hansson under the MIT license. Chapter 18 contains material excerpted from the RSpec source code and API documentation, Copyright © 2005-2007 The RSpec Development Team. The MIT License reads: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, mod- ify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS,” WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PAR- TICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFT- WARE OR THE USE OF OR OTHER DEALINGS IN THE SOFTWARE. Associate Publisher Copy Editor Mark Taub Margaret Berson Acquisitions Editor Proofreader Debra Williams Cauley Kathy Ruiz Development Editor Technical Reviewer Francis Hwang Songlin Qiu Sebastian Delmont Managing Editor Wilson Bilkovich Patrick Kanouse Courtenay Gasking Senior Project Editor Sam Aaron San Dee Phillips Nola Stowe Susan Potter Indexer Jon Larkowski Tim Wright Publishing Coordinator Cindy Teeters Book Designer Chuti Prasertsith Composition Mark Shirar To Desi, my love, my companion, my muse. xii Contents Contents Chapter 1 Rails Environments and Configuration 1 Startup 2 Default Environment Settings 2 Mode Override 2 Rails Gem Version 2 Bootstrapping 3 RubyGems 5 Initializer 6 Default Load Paths 6 Rails, Modules, and Auto-Loading Code 7 Builtin Rails Info 8 Configuration 9 Skipping Frameworks 9 Additional Load Paths 10 Log-Level Override 10 ActiveRecord Session Store 10 Schema Dumper 11 Observers 11 Time Zones 11 Additional Configuration 13 Development Mode 14 Automatic Class Reloading 15 The Rails Class Loader 15 Test Mode 17 Production Mode 17 Logging 18 Rails Log Files 20 Contents xiii Log File Analysis 22 Syslog 24 Conclusion 25 References 25 Chapter 2 Working with Controllers 27 The Dispatcher: Where It All Begins 28 Request Handling 28 Getting Intimate with the Dispatcher 29 Render unto View… 31 When in Doubt, Render 32 Explicit Rendering 33 Rendering Another Action’s Template 33 Rendering a Different Template Altogether 34 Rendering a Partial Template 35 Rendering Inline Template Code 35 Rendering Text 35 Rendering Other Types of Structured Data 36 :json 36 :xml 36 Rendering Nothing 36 Rendering Options 37 :content_type 37 :layout 37 :status 37 Redirecting 39 Controller/View Communication 42 Filters 43 Filter Inheritance 44 Filter Types 46 Filter Classes 46 Inline Filter Method 47 Filter Chain Ordering 47 Around Filters 48 Filter Chain Skipping 49 xiv Contents Filter Conditions 50 Filter Chain Halting 50 Streaming 51 send_data(data, options = {}) 51 Options for send_data 51 Usage Examples 52 send_file(path, options = {}) 52 Options for send_file 53 Usage Examples 55 Letting the Web Server Send Files 55 Conclusion 56 References 56 Chapter 3 Routing 57 The Two Purposes of Routing 58 Bound Parameters 60 Wildcard Components (“Receptors”) 61 Static Strings 62 The routes.rb File 63 The Default Route 65 Spotlight on the :id Field 66 Default Route Generation 67 Modifying the Default Route 68 The Ante-Default Route and respond_to 69 respond_to and the HTTP-Accept Header 70 The Empty Route 71 Writing Custom Routes 72 Using Static Strings 72 Using Your Own “Receptors” 73 A Note on Route Order 75 Using Regular Expressions in Routes 76 Default Parameters and the url_for Method 76 What Happened to :id? 77 Using Literal URLs 79 Route Globbing 79 Globbing Key-Value Pairs 80 Named Routes 81 Contents xv Creating a Named Route 81 The Question of Using name_path Versus name_url 82 Considerations 83 What to Name Your Routes 83 Argument Sugar 84 A Little More Sugar with Your Sugar? 85 The Special Scope Method with_options 86 Conclusion 88 References 88 Chapter 4 REST, Resources, and Rails 89 REST in a Rather Small Nutshell 89 REST in Rails 91 Routing and CRUD 92 Resources and Representations 93 REST Resources and Rails 93 From Named Routes to REST Support 94 Reenter the HTTP Verb 96 The Standard RESTful Controller Actions 96 The PUT and DELETE Cheat 98 Singular and Plural RESTful Routes 98 The Special Pairs: new/create and edit/update 99 Singular Resource Routes 100 Nested Resources 101 Setting :path_prefix Explicitly 103 Setting :name_prefix Explicitly 103 Specifying RESTful Controllers Explicitly 105 All Together Now 105 Considerations 107 Deep Nesting? 108 RESTful Route Customizations 110 Extra Member Routes 110 Extra Collection Routes 111 Considerations 112 Controller-Only Resources 113 Different Representations of Resources 115 xvi Contents The respond_to Method 116 Formatted Named Routes 117 The RESTful Rails Action Set 117 Index 118 Show 121 Destroy 121 New and Create 123 Edit and Update 124 Conclusion 125 Reference 126 Chapter 5 Reflecting on Rails Routing 127 Examining Routes in the Application Console 127 Dumping Routes 128 Anatomy of a Route Object 129 Recognition and Generation in the Console 132 Named Routes in the Console 134 Testing Routes 135 The Routing Navigator Plugin 136 Conclusion 137 References 137 Chapter 6 Working with ActiveRecord 139 The Basics 140 Migrations 142 Creating Migrations 143 Naming Migrations 144 Migration Pitfalls 145 Migration API 146 create_table(name, options) 147 Defining Columns 149 Column Type Mappings 150 Column Options 151 Decimal Precision 152 Column Type Gotchas 152 Custom Data Types 154 “Magic” Timestamp Columns 154 Macro-Style Methods 155 Relationship Declarations 155 Contents xvii Convention over Configuration 156 Pluralization 157 Should I Report INFLECTOR Bugs to the Core Team? 158 Setting Names Manually 158 Legacy Naming Schemes 159 Defining Attributes 160 Default Attribute Values 160 Serialized Attributes 162 CRUD: Creating, Reading, Updating, Deleting 163 Creating New ActiveRecord Instances 163 Reading ActiveRecord Objects 164 find 164 Reading and Writing Attributes 166 Hash Notation 167 The attributes Method 168 Accessing and Manipulating Attributes Before They Are Typecast 168 Reloading 169 Dynamic Attribute-Based Finders 169 Custom SQL Queries 171 The Query Cache 172 Logging 173 Default Query Caching in Controllers 173 Limitations 174 Updating 174 Updating by Condition 176 Updating a Particular Instance 176 Updating Specific Attributes 177 Convenience Updaters 177 Controlling Access to Attributes 178 Deleting and Destroying 178 Database Locking 179 Optimistic Locking 180 Handling StaleObjectError 181 Pessimistic Locking 182 Considerations 183 Advanced Finding 183 Conditions 183 Boolean Conditions 185 Ordering of Find Results 186