Rails does not support to select specific columns when includes
. You know ,it's just lazy load
.
It use the ActiveRecord::Associations::Preloader module to load the associated data before data actually using. By the method:
def preload(records, associations, preload_scope = nil)
records = Array.wrap(records).compact
if records.empty?
[]
else
records.uniq!
Array.wrap(associations).flat_map { |association|
preloaders_on association, records, preload_scope
}
end
end
preload_scope
the third params of preload
, is a way to select specify columns. But can't lazy load anymore.
At Rails 5.1.6
relation = Profile.where(id: [1,2,3])
user_columns = {:select=>[:updated_at, :id, :name]}
preloader = ActiveRecord::Associations::Preloader.new
preloader.preload(relation, :user, user_columns)
It will select the specify columns you passed in. But, it just for single association. You need create a patch for ActiveRecord::Associations::Preloader
to support loading multiple complex associations at once.
Here is a example for patch
The way to use it, example