Page
1
(This page has no text content)
Page
2
Agile Web Development with Rails 7.2
Page
3
(This page has no text content)
Page
4
by Sam Ruby Version: P1.0 (April 2025)
Page
5
Copyright © 2025 The Pragmatic Programmers, LLC. This book is licensed to the individual who purchased it. We don't copy-protect it because that would limit your ability to use it for your own purposes. Please don't break this trust—you can use this across all of your devices but please do not share this copy with other members of your team, with friends, or via file sharing services. Thanks. 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 Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. About the Pragmatic Bookshelf The Pragmatic Bookshelf is an agile publishing company. We’re here because we want to improve the lives of developers. We do this by creating timely, practical titles, written by programmers for programmers. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://pragprog.com. Our ebooks do not contain any Digital Restrictions Management, and have always been DRM-free. We pioneered the beta book concept, where you can purchase and read a book while it’s still being written, and provide feedback to the author to help make a better book for everyone. Free resources for all purchasers include source code downloads (if applicable), errata and discussion forums, all available on the book's home page at pragprog.com. We’re here to make your life easier. New Book Announcements Want to keep up on our latest titles and announcements, and occasional special offers? Just create an account on pragprog.com (an email address and a password is all it takes) and select the checkbox to receive newsletters. You can also follow us on twitter as @pragprog. About Ebook Formats If you buy directly from pragprog.com, you get ebooks in all available formats for one price. You can synch your ebooks amongst all your devices (including iPhone/iPad, Android, laptops, etc.) via Dropbox. You get free updates for the life of the edition. And, of course, you can always come back and re-download your books when needed. Ebooks bought from the Amazon Kindle store are subject to Amazon's polices. Limitations in Amazon's file format may cause ebooks to display differently on different devices. For more information, please see our FAQ at pragprog.com/#about-ebooks. To learn more about this book and access the free resources, go to https://pragprog.com/book/rails72, the book's homepage. Thanks for your continued support, The Pragmatic Bookshelf The team that produced this book includes: Dave Thomas (Publisher), Janet Furlow (COO), Susannah Davidson (Executive Editor),
Page
6
Series editor: Noel Rappin, Adaobi Obi Tulton (Development Editor), Karen Galle (Copy Editor), Potomac Indexing, LLC (Indexing) For customer support, please contact support@pragprog.com. For international rights, please contact rights@pragprog.com.
Page
7
Table of Contents Foreword to the Rails 7 Edition Preface to the Rails 7.2 Edition Acknowledgments Introduction Rails Simply Feels Right Rails Is Agile Who This Book Is For How to Read This Book Part I. Getting Started 1. Installing Rails Installing on Windows Installing on macOS Installing on Linux Choosing a Rails Version Setting Up Your Development Environment Rails and Databases 2. Instant Gratification Creating a New Application Hello, Rails! Linking Pages Together When Things Go Wrong
Page
8
3. The Architecture of Rails Applications Models, Views, and Controllers Rails Model Support Action Pack: The View and Controller 4. Introduction to Ruby Ruby Is an Object-Oriented Language Data Types Logic Organizing Structures Marshaling Objects Pulling It All Together Ruby Idioms Part II. Building an Application 5. The Depot Application Incremental Development What Depot Does Let’s Code 6. Task A: Creating the Application Iteration A1: Creating the Product Maintenance Application Iteration A2: Making Prettier Listings 7. Task B: Validation and Unit Testing Iteration B1: Validating! Iteration B2: Unit Testing of Models 8. Task C: Catalog Display Iteration C1: Creating the Catalog Listing Iteration C2: Adding a Page Layout Iteration C3: Using a Helper to Format the Price Iteration C4: Functional Testing of Controllers
Page
9
Iteration C5: Caching of Partial Results 9. Task D: Cart Creation Iteration D1: Finding a Cart Iteration D2: Connecting Products to Carts Iteration D3: Adding a Button 10. Task E: A Smarter Cart Iteration E1: Creating a Smarter Cart Iteration E2: Handling Errors Iteration E3: Finishing the Cart 11. Task F: Hotwiring the Storefront Iteration F1: Moving the Cart Iteration F2: Creating a Hotwired Cart Iteration F3: Highlighting Changes Iteration F4: Broadcasting Updates with Action Cable 12. Task G: Check Out! Iteration G1: Capturing an Order Iteration G2: Adding Fields Dynamically to a Form Iteration G3: Testing Our JavaScript Functionality 13. Task H: Sending Emails and Processing Payments Efficiently Iteration H1: Sending Confirmation Emails Iteration H2: Connecting to a Slow Payment Processor with Active Job 14. Task I: Logging In Iteration I1: Adding Users Iteration I2: Authenticating Users Iteration I3: Limiting Access Iteration I4: Adding a Sidebar, More Administration 15. Task J: Internationalization
Page
10
Iteration J1: Selecting the Locale Iteration J2: Translating the Storefront Iteration J3: Translating Checkout Iteration J4: Adding a Locale Switcher 16. Task K: Receive Emails and Respond with Rich Text Iteration K1: Receiving Support Emails with Action Mailbox Iteration K2: Storing Support Requests from Our Mailbox Iteration K3: Responding with Rich Text 17. Task L: Deployment and Production Overview of the Changes Configuring the Databases Managing Secrets Building a Docker Image Getting Up and Running 18. Depot Retrospective Rails Concepts Documenting What We’ve Done Part III. Rails in Depth 19. Finding Your Way Around Rails Where Things Go Naming Conventions 20. Active Record Defining Your Data Locating and Traversing Records Creating, Reading, Updating, and Deleting (CRUD) Participating in the Monitoring Process Transactions
Page
11
21. Action Dispatch and Action Controller Dispatching Requests to Controllers Processing of Requests Objects and Operations That Span Requests 22. Action View Using Templates Generating Forms Processing Forms Uploading Files to Rails Applications Using Helpers Reducing Maintenance with Layouts and Partials 23. Migrations Creating and Running Migrations Anatomy of a Migration Managing Tables Advanced Migrations When Migrations Go Bad Schema Manipulation Outside Migrations 24. Customizing and Extending Rails Creating a Reusable Web Component Testing with RSpec Creating HTML Templates with Slim Customizing Rails in Other Ways Where to Go from Here Bibliography Copyright © 2025, The Pragmatic Bookshelf.
Page
12
Early Praise for Agile Web Development with Rails 7 The best book to get started in the Rails world. A comprehensive, coherent, and concise overview of the Ruby on Rails framework. It treats learning in a gradual way, creating an application from scratch using the latest technologies. → Luis Miguel Cabezas Granado Ruby on Rails and PHP developer at Junta de Extremadura (Spain) and PHP book writer at Anaya Multimedia I liked how the book guided me through each step of the tasks. This book gives a thorough introduction to Rails, and I’d suggest it to anyone who wants to start development with Rails. → Gábor László Hajba Software Developer, EBCONT Enterprise Technologies The book was really pleasant to read; I liked how it creates a foundational understanding of Rails with a realistic scenario and then builds upon it for the more advanced topics. → Alessandro Bahgat Software Engineer, Google
Page
13
Foreword to the Rails 7 Edition It’s been a long time since Ruby on Rails was the new kid on the block, but it’s more relevant than ever for developing websites and services. After more than sixteen years since its original release, Rails continues to mature as a platform that helps you get things done. One of the secrets of Rails is something that its creator, David Heinemeier Hansson, calls conceptual compression. A careful building and layering of abstractions let you quickly start a task. Then, if and when you need to go deeper and take more control of a particular aspect of Rails, you can. You’ll see this in every facet of Rails. For example, ActiveRecord—Rails’ database layer—helps you quickly get data in and out of databases yet allows you to drop down to SQL when needed. Another secret of Rails is that it builds on Ruby’s emphasis on optimizing programmer happiness. It makes the process of creating software for the web fun and rewarding. What isn’t a secret is what Rails allowed programmers to do. Some of the biggest software success stories of the last two decades were built and launched on Rails. Shopify, the
Page
14
company I currently work for, is one of those success stories. The same codebase that Tobi Lütke started in 2006, shown in the image, has grown up to serve millions of merchants and process billions of dollars of transactions a week. And we’re still using Ruby on Rails, with no plans to ever quit using it. While we use many other technologies, and will continue to evaluate new ones, Rails and—more importantly—the principles it is built on are at the core of what we do. Now, I’m not going to argue that you should learn and use Rails because it’s what Shopify, GitHub, and many other fantastic companies use. That’s not a very strong argument. However, a strong argument is that companies like Shopify and GitHub use Rails because it’s excellent for what we want to do. And, it might be just the right tool for what you wish to do as well. Even if you go on to use other things,
Page
15
learning Rails will open your eyes to a deeper appreciation of how to build web applications. I still remember the huge smile it gave so many years ago when I first installed the original version of Rails and started to play around with it. At the time, I’d been building for the web for almost a decade and thought that I knew pretty much everything I needed to know. It turns out that I had a lot to learn. And that experience reminds me to this day that there’s still so much to learn. I wish you the best as you start your journey to learning Rails, and I hope it gives you the same big smile that it’s given so many other people as they’ve learned it. Last but not least, you’re in the best of hands. Dave Thomas was the person who helped bring Ruby to the English-speaking world and taught so many of us how to get the most out of the language. And, over two decades, I’ve learned so much from Sam Ruby through all of his work on the web. I consider both of them among the best mentors one can have. With all that said, let’s get started! James Duncan Davidson Distinguished Engineer, Shopify mailto:duncandavidson@me.com Berlin, Germany, 2022-05-01 Copyright © 2025, The Pragmatic Bookshelf.
Page
16
Preface to the Rails 7.2 Edition Rails 7.0 was released in December of 2021. It’s been rock solid in that Rails 7.0 apps can be upgraded to Rails 7.1 and Rails 7.2 with minimal effort. The Rails core team has been working hard to make sure that the upgrade path is as smooth as possible. On the flip side, Rails 7.1 and 7.2 introduced a number of changes that make writing books on the subject a bit more challenging. I’ll give three examples: First, the most mundane: Rails 7.2 introduces RuboCop as the default linter. [1] This is a good thing, but it means that literally every code example in the book had to be checked and updated to pass RuboCop’s checks. This was a lot of work, but it was worth it. Second, the behavior of the destroy action generated by scaffolding has changed, [2] so readers that were following the instructions in the Rails 7.0 edition to get stuck. [3] I had to update the book to reflect the new behavior. Third, Rails 7.1 introduced Dockerfiles for deployment. This is a great feature, but it means that the Deployment chapter
Page
17
[1] [2] [3] [4] [5] [6] had to be completely rewritten. On a personal front, when Rails 7.0 came out I was retired and focusing on my hobby: ballroom dancing. I was enamored of the new Hotwire functionality in Rails and put it to use writing an web application to schedule ballroom dancing events. Once I got more than a few users, it was time to graduate my application from my Mac Mini in my attic to the cloud. I found Fly.io [4] and they were looking for a Rails expert, so I unretired [5] and joined them. I learned a lot about Dockerfiles and contributed heavily to the Rails 7.1 Dockerfile support. [6] One way to look at this is that all of my interests have converged: Rails, this book, ballroom dancing, and Fly.io. Another way to look at this is that I contributed to the need for this book to be updated. In any case, the true winners are the readers of this book. Rails is ever getting better, and this book is ever getting better. I hope you enjoy this edition. Footnotes https://github.com/rubocop/rubocop#readme https://github.com/rails/rails/commit/e87608e355a269a310ee868e73dd3efa f5611f00 https://forum.devtalk.com/t/agile-web-development-with-rails-7-page-118- test-fails-solved/137572 https://fly.io/ https://intertwingly.net/blog/2022/08/13/Unretiring https://github.com/rails/rails/blame/7-1- stable/railties/lib/rails/generators/rails/app/templates/Dockerfile.tt
Page
18
Copyright © 2025, The Pragmatic Bookshelf.
Page
20
Rails is constantly evolving, and as it has, so has this book. Parts of the Depot application were rewritten several times, and all of the text and code was updated. The avoidance of features as they become deprecated has repeatedly changed the structure of the book, as what was once hot became just lukewarm. So, this book would not exist without a massive amount of assistance from the Ruby and Rails communities. And of course, none of this would exist without the developers contributing to Ruby on Rails every day. In particular, the Rails core team has been incredibly helpful, answering questions, checking out code fragments, and fixing bugs— even to the point where part of the release process includes verifying that new releases of Rails don’t break the examples provided in this book. Sam Ruby Copyright © 2025, The Pragmatic Bookshelf.