Earlier quoted context omitted.
There is always an alternative to writing SQL queries by hand, and it's usually a better one IME. Any ORM worth its salt will let you do the query in your blog post via the ORM, as a single query.
> There is always an alternative to writing SQL queries by hand, and it's usually a better one IME. I spent years writing code using Spring/Hibernate, and I can state with certainty that both of those statements are demonstrably false. Every application starts with good intentions, a simple CRUD webapp, and an ORM, then at some point the business requirements yield an N+1 problem in ORMs or several non-trivial left j…
At that point it's far easier to write the query in
straight SQL and produce a straightforward mapping
into the record structure, which doesn't play well
with the ORM because that bypasses its entity cache,
which causes another huge set of problems on its own
Rails' ActiveRecord ORM offers at least two ways to handle this.1. ActiveRecord plays really nicely with views (including materialized views) in my experience. It treats them just like tables, basically, except you can't write to them. (note: there may actually be some cases where you can write to them; not sure)
2. You can supply your own handrolled SQL to ActiveRecord, e.g. `User.find_by_sql("select a,b,c from blahblahblah")`
YMMV obviously but I've been working with Rails since 2014 but this has covered all of my performance needs.
Plain old ActiveRecord default query generation is fine 99% of the time, and it's rather elegant/easy to sidestep it when I wish.