A filterable .includes or a .select with .includes

Hi everyone. I have been in search of something that would allow me to selectively select columns to load into an entity retrieved by using .includes(.preload or .eager_load) like Project.includes(:active_user[:name, :age]) or Project.includes(:active_user).select(:id, active_user: {id: user_id, name: user_name}), similar to what this thread was asking for.

In an effort to try to solve this myself, I ran into the following problems:

  1. inability to find what the true aliases are when the same table is joined on multiple times in the same query
  2. inability to use .select with .includes
  3. inability to get back a nest structure like what you would normally get with ActiveRecord::Relation

For #1 and #2, fortunately, I found this gem, Brick, which makes .select work with .include as well as attempting to figure out what the aliases that are generated by AREL are. Although this partially solves the 1st and 2nd problem, its limitation of this solution is that it only work with joins, and the result is not nested.

For making this work with preload i have tried messing with preload_association, it only works to an extent.

Before going too deep into this only to realize that its a wasted effort, I would like to ask you if this is a reasonable effort and if im going down the right path?

Does anyone have insight into the viability of making this part ot default Rails? Im still in the process of solving this problem myself, but if it works, i would like to contribute to Rails. However, i might be missing something thats prevents anyone trying to implement this patch.

2 Likes

Heya Chuan!

Glad to be along with you on this quest. I think perhaps The Brick can bring back the nested ActiveRecord objects in a way that would be useful. Can record a demo of this later in the evening, about 5 hours from now.

(Somewhat coincidentally Iā€™m currently on my way out to Manchester in order to give a demo of Brick!)

-L

Hopefully this video can demonstrate a little more clearly how Brick can be useful to optimise database queries when eager loading ā€“ notice that everything gets returned as nested ActiveRecord objects :slight_smile: