Page
1
(This page has no text content)
Page
2
The Rails 8 Way Lucas Dohmen, Tom Henrik Aadland, and Obie Fernandez This book is available at https://leanpub.com/therails8way This version was published on 2025-07-21 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2024 - 2025 Lucas Dohmen, Tom Henrik Aadland, and Obie Fernandez
Page
3
Contents Foreword (Rails 7 Way) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Cover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 About the Authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Book Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Licenses, Attributions and Trademark Notice . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Rails Configuration and Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Generating a new Rails Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Bundler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 RSpec and Haml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 JavaScript and CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Foreman and Overmind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Running a Rails application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Common Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Zeitwerk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Development Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Test Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Production Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Configuring Application Secrets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Configuring a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Health Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Default Gems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Dependency Updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Static Code Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 TLS (Transport Layer Security) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Rack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Page
4
CONTENTS Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 The Two Purposes of Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 The routes.rb File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Named Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Scoping Routing Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Listing Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 REST, Resources, and Rails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 REST in a Rather Small Nutshell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Resources and Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 REST in Rails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Routing and CRUD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 The Standard RESTful Controller Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Singular Resource Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Nested Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Routing Concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 RESTful Route Customizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Controller-Only Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Different Representations of Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 The RESTful Rails Action Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Working with Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Action Dispatch: Where It All Begins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Render onto View… . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Additional Layout Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Redirecting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Controller/View Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Action Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Streaming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 The respond_to Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Allow Browsers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Rate Limiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Cookies, Session Management and the Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 The Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 What to Store in a Cookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 What to Store in the Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Page
5
CONTENTS Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 Action View & Haml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Haml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Layouts and Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 Partials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Active Record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 Creating Migrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 Defining Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 Schema and Sequencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Seeding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 Database-Related Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Working with Active Record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Model Mass-assignment Attributes Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 SQL Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 Localized Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 I18n Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 Setting and Passing the Locale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Setting Locale from Client Supplied Information . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Internationalizing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Organization of Locale Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 Looking Up Translations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 How to Store Your Custom Translations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 Building forms with form_with . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 Form Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 RSpec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Behavior-Driven Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 Basic Syntax and API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 Custom Expectation Matchers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Helper Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Shared Behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 Shared Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Page
6
CONTENTS Test Doubles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 Running Specs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 Testing Tool Belt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Authentication and Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Devise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Pundit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 Active Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 Uploading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 Representations and Variants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Removing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Production . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Background Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 Active Job . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 Queueing Backends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 Sending and Receiving Mails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Mailer Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Previews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 Action Mailbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 Cache Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Cache Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 Initializing New Caches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 Fragment Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 Generational Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 Collection Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 Conditional Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 Expiration of Cached Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 Automatic Cache Expiry with Sweepers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Cache Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 Our application in production . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 Kamal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 Platform as a Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
Page
7
CONTENTS Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Wrap Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Page
8
Foreword (Rails 7 Way) If this book is your first introduction to the Rails framework and community, welcome! If you’ve been away from Rails for a while, welcome back. And if you’re a seasoned Rails programmer, nice to see you again. I’m so glad you’re all here. Rails is not just a framework, but a vibrant community of people who care about developer happiness. I first started working with Rails around 2012, shortly after Rails 3.2 was released. Ruby on Rails was still a relatively new framework and new releases weren’t always stable. Regardless, the Ruby community lovedworkingwith Rails and so numerous companies were built using it; many of which are still thriving on Rails today. It’s been amazing to watch the framework and community evolve and grow over the years. In 2014 I spoke at my first Ruby conference at Mountain West Ruby. It was there that I met Aaron Patterson (aka tenderlove) who told me I had found a bug in Active Record and we should work on fixing it together. We started pairing weekly and I became a regular contributor to the framework. In 2017 I was invited to join the Rails Core Team – we are the team behind the long term vision of the framework. We are focused on new features, stability, and ensuring that Rails continues to evolve with application needs. Since joining the Core Team I have focused on improving Rails to work well with applications as they grow by focusing on database scalability and performance. In Rails 6 and 7, I implemented support for multiple databases and database sharding (referenced in this book in the Multiple Databases Section). The Rails framework is unique because it has matured alongside the companies that use it. We’re not exaggerating when we say that Rails can take you from “Hello, World!” to IPO; so many applications that were started on Rails 1.0 are not just running today, but thriving. This evolution and symbiotic relationship between Rails and the companies that use it come from the belief the community has in contributing to open source. The companies that depend heavily on Rails success know they have a direct role in that success. Without contributors there would be no Rails and I’m incredibly proud of the community we’ve built. I hope that this book is helpful for you to learn how to start writing Rails applications and that you enjoy being a part of this community. Even more though, I hope that this is a jumping off point for you. When you hit bugs in your application, dig deeper and find out why the bug occurred. You might just find a bug in the framework and become a Rails contributor and member of the Rails Core Team. That’s how I started contributing to Rails, just a couple years after learning how to program. Remember that technical books are the beginning of your learning adventure, not the end. —Eileen M. Uchitelle (@eileencodes), Rails Core Team
Page
9
Foreword (Rails 7 Way) 2 Cover The cover is designed by Studio Rohrspatz¹ and based on a photo of grey and brown dock² by Max Lawton³ published under the Unsplash License. The font used is Fixel by MacPaw⁴ published under the Open Font License. ¹https://rohrspatz.studio ²https://unsplash.com/photos/photo-of-grey-and-brown-dock-hGiYdXIo7-w ³https://unsplash.com/@maxwelllawton ⁴https://fixel.macpaw.com
Page
10
About the Authors The “one and only” Obie Fernandez⁵ is an avid writer and technology enthusiast, in addition to achieving worldwide success as an electronic music producer and touring DJ. He is Co-founder and Chief Scientist of AI platform Olympia⁶, and also Partner and Chief Consultant at MagmaLabs⁷, a powerhouse Ruby on Rails consultancy. Obie has been the founder of Hashrocket⁸, as well as CTO and co-founder of many startups including Mark Zuckerberg’s beloved Andela⁹ and Trevor Owen’s Lean Startup Machine. His latest book is Patterns of Application Development Using AI¹⁰. Lucas Dohmen¹¹ is an experienced software engineer and team lead, systems architect, consultant and trainer. Two decades’ worth of experience across different technologies and organizations. Co-author of “The Rails Way” book series. Seasoned conference speaker and podcaster. Founder and maintainer of multiple open-source projects. Particularly enjoys collaborating remotely and asynchronously, helping people and organizations grow their potential. Tom Aadland is the VP of Development at EG Facility & Energy Management, where he provides strategic direction and leadership for the development department, ensuring that all goals align with the company’s overall objectives. Passionate about development and all things technology, Tom is committed to fostering a culture of excellence, continuous improvement, and a happy, healthy environment within the organization. ⁵https://obiefernandez.com/about ⁶https://olympia.chat ⁷https://magmalabs.io ⁸http://hashrocket.com ⁹http://andela.com ¹⁰https://leanpub.com/patterns-of-application-development-using-ai ¹¹https://lucas.dohmen.io
Page
11
Acknowledgments We would like to thank these remarkable people for giving us in depth feedback on The Rails 6, 7 and 8 Way, in alphabetical order: • Bascht Schulze • Bodo Tasche • Daphne Waporidis • Dirk Breuer • Eileen M. Uchitelle • FND • Joachim Praetorius • Lars Hupel • Martin Otten • Simon Kölsch • Tobi Eilert
Page
12
Introduction Rails™ 8 has the following big themes: “Make deployments easier” is basically the release subtitle. A fresh Rails application now comes with a Dockerfile ready for production traffic. Thruster¹² is a reverse proxy that will take the incoming requests into your Docker container, which then sends the traffic to an application server like Puma. It adds HTTP/2 support, automatic TLS certificate management, and serves your static files efficiently. Kamal¹³ is a deployment tool like Capistrano for a dockerized application. It configures a fresh Linux box to run your application behind the new Kamal Proxy¹⁴ for zero- downtime deployments. We explain how this works in our entirely new Deployment chapter. “No Redis required” is the second big theme. For years, most Rails applications had their primary database (like Postgres) plus Redis as their sidekick. Solid Cache¹⁵ is an Active Support cache store, and Solid Cable¹⁶ is an Action cable adapter. Both use your database instead of Redis (or memcached). The third library is Solid Queue¹⁷, an Active Job adapter that works similar to GoodJob¹⁸ (the adapter we recommended in previous editions). Compared to GoodJob, Solid Queue has one advantage: It also works with MySQL and SQLite. The Rails™ 8 Way is the comprehensive, authoritative reference guide for professionals delivering production-quality code using modern Ruby on Rails. It illuminates the entire Rails 8 API, its most powerful idioms, design approaches, and libraries. Building on the previous editions, this edition has been heavily refactored and updated. After all the additions we made to The Rails 7 Way, it became clear that the book had turned into a tome. As we still have more things to share, we decided to split the book into three parts. This is the first book, going over the entire framework. Apart from that, we have two more books coming soon: • Rails Way: ActiveRecord Deep Dive¹⁹ — this will go into the advanced topics of Active Record, covering every detail of this important part of Rails. • Building ProgressiveWebApps with Rails²⁰ —whichwill answer your question: How do I build a modern web frontend with Rails, entirely without an SPA framework like React, Angular, or Vue? As with previous editions, this book is not a tutorial or a basic introduction to Ruby or Rails. The idea is for the full-time Rails developer to give it a once-over straight through at first, then use it ¹²https://github.com/basecamp/thruster ¹³https://github.com/basecamp/kamal ¹⁴https://github.com/basecamp/kamal-proxy ¹⁵https://github.com/rails/solid_cache ¹⁶https://github.com/rails/solid_cable ¹⁷https://github.com/rails/solid_queue ¹⁸https://github.com/bensheldon/good_job ¹⁹https://leanpub.com/active_record_deep_dive ²⁰https://leanpub.com/pwas-with-rails
Page
13
Introduction 6 as a day-to-day reference. The more confident reader might get started in Rails using just this book, extensive online resources, and their wits. Still, other publications are more introductory and might be a wee bit more appropriate for beginners. To make the most of this book, you should be at least somewhat familiar with how to bootstrap a Rails application and the MVC (Model-View-Controller) architectural pattern. Every contributor to this book has worked professionally with Rails for a long time. We do not spend our days writing books or training other people, although that is certainly something that we enjoy doing on the side. Obie initially wrote this book for himself because he hated having to use online documentation, especially API docs, which need to be consulted repeatedly. Since the API documentation is liberally licensed, just like the rest of Rails, some book sections draw from the API documentation. But in practically all of those cases, the API documentation has been expanded and/or corrected, supplemented with additional examples, and enhanced with commentary drawn from practical experience. Sample Code and Listings The domains chosen for the code samples should be familiar to almost all professional developers. They include time and expense tracking, auctions, regional data management, and blogging applications. We don’t spend pages explaining the subtler nuances of the business logic for the samples or justify design decisions that don’t directly relate to the topic at hand. Following in the footsteps of Hal Fulton and The Ruby Way, most of the snippets are not full code listings—only the relevant code is shown. Ellipses (…) often denote parts of the code that have been eliminated for clarity. The whole set of code listings will not add up to a complete working system, nor are there 30 pages of sample application code in an appendix. The code listings should serve as inspiration for your production-ready work, but keep in mind that it often lacks the touches necessary in real-world work. For example, examples of controller code are often missing pagination and access control logic because it would detract from the point we want to express. Concerning Third-Party RubyGems and Plugins Whenever you write code that feels like plumbing, by which we mean entirely unrelated to the business domain of your application, you’re probably doing too much work. We hope you have this book at your side when you encounter that feeling. There is almost always some new part of the Rails API or a third-party RubyGem for exactly doing what you are trying to do. Part of what sets this book apart is that we never hesitate to call out the availability of third-party code. We even document the RubyGems and plugins that we feel are crucial for effective Rails work. In cases where 3rd-party code is better than the built-in Rails functionality, we don’t cover the built- in Rails functionality (pagination is a good example).
Page
14
Introduction 7 An average developer might see their productivity double with Rails, but we’ve seen serious Rails developers achieve gains that are much, much higher. That’s because we follow the Don’t Repeat Yourself (DRY) principle, of which Don’t Reinvent The Wheel (DRTW) is a close corollary. Reimplementing something when an existing implementation is good enough is an unnecessary waste of time that nevertheless can be very tempting since it’s such a joy to program in Ruby. Ruby on Rails is a vast ecosystem of core code, official plugins, and third-party plugins. That ecosystem has been exploding rapidly and provides all the raw technology you need to build even the most complicated enterprise-class web applications. Our goal is to equip youwith enough knowledge that you’ll be able to avoid continuously reinventing the wheel. Goals As already stated, we hope tomake this your primaryworking reference for Ruby on Rails. Over time we hope this book gives you as an application developer/programmer greater confidence in making design and implementation decisions while working on your day-to-day tasks. After spending time with this book, your understanding of the fundamental concepts of Rails coupled with hands-on experience should leave you feeling comfortable working on real-world Rails projects with real- world demands. Finally, if you are a development manager, you should find the practical perspective of the book and our coverage of testing and tools especially interesting and hopefully get some insight into why your developers are so excited about Ruby and Rails. Prerequisites The reader is assumed to have the following knowledge: • Basic Ruby syntax and language constructs such as blocks • Solid grasp of object-oriented principles and design patterns • Basic understanding of relational databases and SQL • Familiarity with how Rails applications are laid out and function • Basic understanding of network protocols such as HTTP and SMTP • Basic understanding of JSON and web services • Familiarity with transactional concepts such as ACID properties Book Structure We attempted to give the material a natural structure while trying to be the best-possible Rails reference book. To that end, we have given careful attention to presenting holistic explanations of
Page
15
Introduction 8 each subsystem of Rails, including detailed API information where appropriate. Every chapter is slightly different in scope, and we suspect Rails is now too big a topic to cover the whole thing in depth in just one book. This book does not progress from easy material in the front to harder material in the back. Some chapters do start with fundamental, almost introductory material and push on to more advanced coverage. There are sections of the text that experienced Rails developers will gloss over. However, we believe that there is new knowledge and inspiration in every chapter for all skill levels. Believe us, it has not been easy coming up with a structure that makes perfect sense for everyone. Particularly, we have noted surprise in some readers when they notice that Active Record is not covered first. Rails is foremost a web framework and, at least to us, the controller and routing implementation is the most unique, powerful, and effective feature, with Active Record following a close second. Licenses, Attributions and Trademark Notice “Rails”, “Ruby on Rails”, and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved. Portions of the text are derived or excerpted from the Ruby on Rails source code, Copyright (c) 2005-2023 David Heinemeier Hansson. Portions of the manuscript are derived from RailsGuides, licensed under a Creative Commons Attribution-ShareAlike 4.0 International License https://creativecommons.org/licenses/by-sa/4.0/
Page
16
Rails Configuration and Environments Few formal dining experiences are as revered or as intimidating as omakase —Michelin Guide Rails applications have always been preconfigured with three standard modes of operation: devel- opment, test, and production. These modes are execution environments and have a collection of associated settings that determine things such as which database to connect to and whether the classes of your application should be reloaded with each request. It is simple to create your own custom environments if necessary. The current environment can be specified via the environment variable RAILS_ENV, which names the desired mode of operation and corresponds to an environment definition file in the config/en- vironments folder. You can also set the environment variable RACK_ENV, or as a last resort, you may rely on the default being development. Since this environment setting governs some of the most fundamental aspects of Rails, such as class loading, to understand the Rails way, you should understand its environment settings. We kick off this chapter by generating a Rails application and our options when doing so. Then we cover Bundler, a tool that manages dependencies for Ruby applications. Later in the chapter, we move on to how Rails starts up and handles requests by examining scripts such as boot.rb, application.rb, the default initializers, and some suggestions for custom ones. We will then discuss the Rails Class Loader, which automatically loads classes by examining their names. After that, we look at the settings that make up the three standard environment settings (modes). Finally, we will discuss application secrets, the database configuration, logging, the default set of Gems that comes with Rails and Rack. Generating a new Rails Application To start a new Rails application, we run the command rails new time-and-expenses to generate it. It will create a skeleton Rails application, including the setup for bundler and git. The command is entirely configurable. Let’s go over the most important ones: Configure which database you want to use with the -d option. The default is sqlite3, but you can also configure postgresql (our recommendation) or trilogy (for MySQL/MariaDB). You can skip loading parts of Rails itself with the options: • --skip-action-cable • --skip-action-mailbox
Page
17
Rails Configuration and Environments 10 • --skip-action-mailer • --skip-action-text • --skip-active-job (implies skipping Action Mailer and Active Storage) • --skip-active-record (implies skipping Active Storage and Solid) • --skip-active-storage (implies skipping Action Mailbox and Action Text) • --skip-asset-pipeline • --skip-solid You can also skip generating a few files and dependencies: • --skip-git skips git init, .gitignore and .gitattributes • --skip-docker skips Dockerfile, .dockerignore and bin/docker-entrypoint • --skip-devcontainer skips generating the devcontainer. • --skip-keeps skips source control .keep files • --skip-javascript skips JavaScript files (implies skipping Hotwire) • --skip-hotwire skips Hotwire integration • --skip-jbuilder skips the JBuilder gem for building JSON responses • --skip-test skips generating test files • --skip-system-test skips generating system test files • --skip-bootsnap skips the Bootsnap gem • --skip-dev-gems skips the development gems like web-console • --skip-thruster skips adding the thruster reverse proxy • --skip-rubocop skips the Rubucop setup • --skip-brakeman skips the Brakeman setup • --skip-ci skips the GitHub Actions setup • --skip-kamal skips adding the deployment tool kamal And finally, you can choose your asset pipeline setup: • --js=: importmap (default), bun, webpack, esbuild, or rollup • --css=: tailwind, bootstrap, bulma, postcss, sass (nothing by default) Note that you will need Node and yarn installed for the webpack, esbuild and rollup JavaScript options. The same is true for the tailwind, bootstrap, bulma, postcss and sass CSS options. You can use the --api (skips JavaScript and asset pipeline) and --minimal (skips everything in Rails except Active Record plus all optional gems like Bootsnap) options to preconfigure your Rails app as a pure back-end application or only the essential parts of Rails and its gems. But we recommend a more fine-grained approach.
Page
18
Rails Configuration and Environments 11 We usually skip everything except Active Record, Active Job and the asset pipeline and add them when needed. We also skip the Minitest integration, as we use RSpec and JBuilder as we rarely need to build JSON APIs. We also skip Hotwire as we add it later if we need it. Find more about the pipelines and libraries in our section about JS and CSS. Now add your prefered database, JavaScript and CSS option, and put them in the file ∼/.config/rails/railsrc. Here is an example: --database=postgresql --javascript=esbuild --css=postcss --skip-action-cable --skip-action-mailbox --skip-action-mailer --skip-action-text --skip-active-storage --skip-hotwire --skip-test --skip-jbuilder --skip-kamal If you run rails new time-and-expenses now, it will only include the parts you want to use. We will also add some things, but first, we need to discuss how Rails handles dependencies. Bundler Bundler²¹ is not a technology specific to Rails, but it is the way to manage your application’s Rubygem dependencies. Applications generated with Rails use Bundler automatically, and bundler is a dependency of Rails itself. One of the most important things that Bundler does is dependency resolution on the full list of gems specified in your configuration, all at once. For an interesting perspective concerning how Bundler was conceived, make sure to read Yehuda Katz’s blog post on the subject²². Gemfile The root of your Rails project directory contains a Ruby-based gem manifest file named simply Gemfile, with no filename extension. The Gemfile specifies all dependencies of your Rails app, including the version of Rails being used. The basic syntax for the Gemfile is super simple: ²¹http://bundler.io ²²http://yehudakatz.com/2010/04/21/named-gem-environments-and-bundler/
Page
19
Rails Configuration and Environments 12 gem 'kaminari' gem 'nokogiri' The gem directive takes an optional second argument describing the version of the Rubygem desired. Leaving the version argument off will get the latest available stable version, which may not be the latest version available. To include a release candidate or a pre-release gem you have to to specify the version explicitly. The format of the version argument matches the RubyGem versioning scheme: gem 'nokogiri', '1.5.6' gem 'decent_exposure', '~> 2.0.1' gem 'draper', '1.0.0.beta6' You can find full instructions on how to craft a version string in the RubyGems documentation²³. Every time you modify the Gemfile, or more specifically, if you introduce dependencies not yet installed, invoke the bundle install command to ensure that all the dependencies in your Gemfile are available to your Rails application. Rails requires all Gems in the Gemfile when starting up. To load a dependency only in a specific environment, place it in a group block specifying one or more environment names as symbols: group :development, :test do gem "debug", platforms: %i[ mri mingw x64_mingw ] gem "rspec-rails" end group :development do gem "web-console" end Occasionally, the name of the gem that should be used in a require statement differs from the name of that gem in the repository. In those cases, the :require option solves this declaratively right in the Gemfile: gem 'webmock', require: 'webmock/rspec' It is also possible to load Gems from a Git repository²⁴. You can use a gem that you are actively developing on your local workstation using the :path option: ²³https://guides.rubygems.org/patterns ²⁴https://bundler.io/v2.2/guides/git.html
Page
20
Rails Configuration and Environments 13 gem 'nokogiri', path: '~/code/nokogiri' Gemfile.lock Every time you run bundle install or bundle update, Bundler calculates the dependency tree for your application. Gemfile.lock is a representation of that dependency tree with locked down versions of all dependencies: GEM remote: https://rubygems.org/ specs: actioncable (7.0.1) actionpack (= 7.0.1) activesupport (= 7.0.1) nio4r (~> 2.0) websocket-driver (>= 0.6.1) actionmailbox (7.0.1) actionpack (= 7.0.1) activejob (= 7.0.1) activerecord (= 7.0.1) activestorage (= 7.0.1) activesupport (= 7.0.1) mail (>= 2.7.1) net-imap net-pop net-smtp The first time you run bundle install, no Gemfile.lock file exists yet (it is invoked automatically upon bootstrapping a new Rails application using the rails new command in your terminal). Bundler will start by fetching all remote sources, resolving dependencies, installing needed gems and creating the Gemfile.lock. Re-running bundle install without updating the Gemfile will cause Bundler to re-fetch all remote sources but use the dependencies specified in the Gemfile.lock instead of resolving dependencies again. Under normal circumstances, this changes nothing about your configuration. The most common situation is that a Gemfile.lock exists, and you have updated your Gemfile by adding or changing a dependency. When running bundle install the dependencies specified in Gemfile.lock will be used for gems that did not change, but dependencies will be re-resolved for any gems that were updated. Once a lock file is created, Bundler will only load specific versions of gems you were using at the moment that the Gemfile was locked. You lock your configuration down to using versions of dependencies that you know will work well with your application.