Hi I’d like to propose a new method in AR that allows for specifying selected attributes over preloaded relations, including nested ones. Here’s the core concept:
Objective
Enable SQL SELECT
functionality over preloaded associations to optimize data retrieval when working with nested relations. Currently, preloading fetches all columns, but in many scenarios, only specific attributes are needed, which can lead to unnecessary data loading.
Proposal
Introduce a new select_preload
method for ActiveRecord that:
- Accepts a hash where each key is a relation, and each value is an array of attributes to select.
- Supports nested preloads.
- Requires foreign keys for nested preloads to be specified manually.
Example Usage
Suppose we have a model Model
that has a foreign key to SomeModel
, and SomeModel
has a foreign key to OtherModel
.
Using this new method, we could preload and select specific attributes as follows:
models = Model.preload(some_model: :other_model)
.select_preload(some_model: [:attr1, :other_model_id, other_model: [:foo, :bar]])
models.each do |m|
m.some_model.other_model.foo
end
Expected Queries
The above would generate these SQL queries:
SELECT models.* FROM models
SELECT some_model.id, some_model.other_model_id, some_model.attr1 FROM some_model WHERE some_model.id IN (?)
SELECT other_model.id, other_model.foo, other_model.bar FROM other_model WHERE other_model.id IN (?)
Benefits
- Reduces memory usage by only loading selected columns.
- Reduces query time, particularly when preloading large sets of data.
here’s a draft
Looking forward to your feedback!