tldr: Allow adding columns calculated on-the-fly to an ActiveRecord relation, then manipulate those like regular DB columns.
rationale by an example: Suppose we want to report the histogram of the number of likes per post.
We could load all posts and likes in memory and count in Ruby but that would be inefficient. Instead, we would like to use a column `likes_count` as if it was a regular column stored in DB (counter caching would be another option). To do that, SQL forces us into adding the column on the fly, and then wrapping the query in a subquery to use it in a group statement.
The SQL we're looking to generate is the following: ``` SELECT likes_count, COUNT(*) FROM ( SELECT *, (SELECT COUNT(*) FROM likes WHERE post_id = posts.id) AS likes_count FROM posts ) posts GROUP BY likes_count ```
It would be great to be able to write just this:
class Post < ApplicationRecord scope :decorate_with_likes_count, -> do decorate_with(:likes_count, 'SELECT COUNT(*) FROM likes WHERE post_id = posts.id') end end