SQL and Active Record for junior Rails developers
Demystifying the database
March 6, 2022 · Felipe Vogel ·Databases are hard. A few months ago when I started learning Ruby on Rails, I had trouble shifting from a pure Ruby mindset (where I manipulate data via Ruby’s lovely Enumerable methods) to an Active Record mindset (where I manipulate data from the database as part of a query and not via Enumerable methods). I also kept putting off learning SQL because it was intimidating. Instead I doubled down on Rails basics and testing. Those were great time investments, but now the time has come to learn SQL and Active Record beyond the basics.
Knowing how to use the database wisely and efficiently is one of the most important skills to learn even if you’re still a beginner at Rails. If a Rails app is suffering from performance problems, there’s a good chance it’s because of inefficient database queries. Even tiny hobby apps can suffer from massive (as in, 30 seconds!) page load delays due to clumsy use of Active Record, as I discovered firsthand.
But this is also one of the areas where I found the least guidance, so I’ve compiled my favorite resources below for the benefit of any other lost souls out there. You might also want to check out my complete list of learning resources on Ruby, Rails, and computer science.
SQL resources are listed first here, but that’s not meant as a recommendation to become an SQL expert before learning more about Active Record. I think it’s best to learn both in tandem.
SQL resources
SQL basics
- Databases course at The Odin Project
- SQL Teaching interactive tutorial
- SQLBolt interactive tutorial
- SQLZoo interactive tutorial
SQL exercises
Deeper into SQL
- Use the Index, Luke!
- Advanced Topics in SQL course from Stanford
Active Record resources
- Advanced Active Record at the Odin Project
- The Rails Guides on Active Record
- Some nice Active Record docs from the Rails API Documentation
- Advanced ActiveRecord Querying on Upcase
- An upcoming course on Active Record
Model design and architecture
I’m still looking for a good book or course on this, but in the meantime here are some helpful blog posts.
- How to design and prep a Ruby on Rails model architecture
- Ruby on Rails Model Patterns and Anti-patterns
- Posts on Code with Jason, such as What is a Rails model?, How I organize my Rails apps, and What to do about bloated Active Record models.
- Pro tip for building PORO models: inherit
ActiveModel::Model
and/orActiveModel::Attributes
if you want the conveniences of an Active Record object without actually storing it in the database.
- Pro tip for building PORO models: inherit
- Do a web search for “Rails refactor fat model” if you want more blog posts along those lines.