Is there way to mark Rails scope as loaded (and pass it the records array) to avoid extra db calls?

I have a method which returns an array of records which I can’t keep as a pure scope because I need to do complex in-memory filtering not easy with pure SQL.

accounts = current_user.accounts.select {|a| a.some_complex_method }

But I need to be able to scope-chain it for other purposes later, so I end up re-scoping it:

accounts = Account.where(id: accounts.map(&:id)).order(‘name asc’)

Unfortunately this issues a 2nd db call which isn’t needed because all data for the subsequent scope chains should be available from the original result.

Is there a way for me to build an in-memory chainable scope for data returned previously and already converted to array, without making extra db calls? I realize stuff like offset will not reliably work with this approach, but I don’t need it for my use case.

Eugene

looks like you want a repository on top of activerecord and afaik it’s not really feasible. what i’d suggest in your particular case is to retrieve records in question once and then filter/order them on your own.