You know how the story goes: Once upon a time, there were three little devs. Smart and determined, the three developers set up a new Rails app.
The first little dev, the youngest and littlest, wrote a handful of ActiveRecord conditions in SQL.
All was well, and the queries worked! So it was, and so it continued, for several minutes. But as the littlest dev carried on, innocently combining his scopes, he was interrupted by a big, bad bug. The bug snarled, “Little dev, little dev, just call it quits!”
The littlest dev was having none of this. “Not by the code in my github commits!”
“Then I’ll huff, and I’ll puff, and I’ll raise an exception!” shouted the bug, who proceeded to do just that.
The littlest dev fled in terror to the chat window of his brother, the second little dev, who was a little bit wiser and a little bit bigger (relatively speaking, of course). He nodded solemnly as his younger brother explained what had happened.
Putting on his bravest demeanor, he announced, “Let’s refactor, and chase off that big, bad bug once and for all!”
They worked tirelessly for minutes upon minutes, using the squeel gem to replace their old SQL conditions with robust, readable Ruby code.
Just as they finished adding in a new query, the big, bad bug arrived yet again, displaying an uncanny sense of plot and timing. “Little devs, little devs, just call it quits!”
“Not by the code in our github commits!” came the obvious response from the little devs.
“Then I’ll huff, and I’ll puff, and I’ll raise an exception!” roared the bug. Sure enough, he huffed, and he puffed, and it turned out that the devs had made a typo in their new query, a direct result of too much code duplication.
The two little devs opened a group chat with their eldest brother, the third little dev, who was much wiser and much bigger (relatively speaking, of course). He nodded solemnly as his brothers explained what had happened. Confidence radiating from his monitor-tanned face, he spoke slowly and calmly, “Let’s refactor, and chase off that big, bad bug once and for all.”
The brothers worked tirelessly for at least a few seconds, using ActiveRecord::Relation’s merge method to reduce the duplication of logic in their queries.
The big, bad bug did not show up again, and the three little devs lived happily, for at least a little while.
I’m sorry—you don’t think this sounds familiar? The version you know involves pigs building houses made of straw, sticks, and bricks? And a wolf with improbable lung capacity? This is no time for make-believe; I’m telling the story the way my father told it to me, and his father told it to him.
Like all good stories, this one has a moral: Use squeel and ActiveRecord::Relation#merge to reduce the complexity and duplication of your ActiveRecord queries. Who knows? Maybe you too can live happily, at least for a little while.