As other people have noted, using .select(...)
gets overridden if there's an .includes(...)
. And I didn't like that ... so I figured out a patch to make it work and released it as a part of The Brick.
By overriding ActiveRecord::Associations::JoinDependency.apply_column_aliases()
like this then when you add a .select(...)
then it can act as a filter to choose which column aliases get built out.
With gem 'brick'
loaded, in order to enable this selective behaviour, add the special column name :_brick_eager_load
as the first entry in your .select(...)
, which turns on the filtering of columns while the aliases are being built out. Here's an example:
Employee.includes(orders: :order_details)
.references(orders: :order_details)
.select(:_brick_eager_load,
'employees.first_name', 'orders.order_date', 'order_details.product_id')
Because foreign keys are essential to have everything be properly associated, they are automatically added, so you do not need to include them in your select list.
Hope it can save you both query time and some RAM!