# \[Proposal\] Support SQL SELECT Over Preloaded Relations in Rails

**URL:** <https://discuss.rubyonrails.org/t/proposal-support-sql-select-over-preloaded-relations-in-rails/87885>\
**Category:** rubyonrails-core\
**Tags:** feature, activerecord\
**Created:** [November 8, 2024, 7:35pm UTC](https://discuss.rubyonrails.org/t/proposal-support-sql-select-over-preloaded-relations-in-rails/87885 "2024-11-08T19:35:20Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mera](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/mera/32/12669_2.png) [@mera](https://discuss.rubyonrails.org/u/mera)\
**Post date:** [November 8, 2024, 7:35pm UTC](https://discuss.rubyonrails.org/t/proposal-support-sql-select-over-preloaded-relations-in-rails/87885/1 "2024-11-08T19:35:20Z")

</div>

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:

```ruby
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:

1. `SELECT models.* FROM models`
2. `SELECT some_model.id, some_model.other_model_id, some_model.attr1 FROM some_model WHERE some_model.id IN (?)`
3. `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](https://github.com/meraioth/rails/commit/f7aa79aa6c8c9bf4c3b3027c8881fdcf5ea7e580)

Looking forward to your feedback!
