Nowadays, Rails is the most popular framework for bootstrapping web services.
All services need to read and write their data somehow. In other words, they need to work with a database. Rails does this job really well in a modern and simple way.
As you may know, the framework brings you ActiveRecord (AR) which is find really useful. I think that AR is the most successful part of Rails despite many articles criticising its design and many other problems
But these architectural issues are not the focus of this article. Let's talk about organizing SQL queries in Rails.
Scopes, relations, Arel simplify building general purpose SQL queries like select * from users where id = ?
. You just need to break queries into logical blocks, organize scopes and combine them. But what if we have SQL-heavy queries with a lot of statements and even with CTE
? Breaking such SQL queries into scopes is not a simple task and often it's not the best solution. After analyzing many of our projects we have collected the most popular approaches that help us solve many problems when we dive into the SQL-Hell. Let's talk about them.