[Feature proposal] Injection of values into models for building active record queries

Let’s say you have a model like this:

class Post
  has_many :comments, ->(post) { where(author_id: 1) }

this allows for a static comparison against a constant author id in the post => comments relationship, which is great because it works across joins and the like (Blog.joins(posts: :comments).where(comments: { ... })).

But this feels slightly limiting because it seems like I don’t really have a great degree of query-specific dynamism here. To clarify, what I would like to say is something more like this:

Blog.inject(author: current_user) # specify some values for this one query
    .joins(posts: :comments)
    .where(comments: { ... })

class Post
  has_many :comments, ->(post) { where(author_id: injected[:author].id) }

Perhaps not called inject because of Enumerable#inject, but a similar idea.

A quick poke around stack overflow indicates that people seem to run into some flavour of this a fair amount (accessing user/session information on the model). It’s one thing if it’s just a method on the model, if you can just pass the user as an extra arg, but for these scopes it doesn’t seem so straightforward.

Most of the solutions involve storing some sort of value on the current thread, which doesn’t seem that satisfactory. But I’m open to other solutions of anyone has any suggestions!

Is this the sort of feature that would be useful for Active Record, or should I keep looking into other workarounds?

if comments table has author_id column, the query should be Blog.joins(posts: :comments).where(comments: {author_id: values})

values will be array or integer. I think this way is simple as well.