Related to #35210.
We sometimes use `select` to limit unused columns for performance.
For example, `GET /posts/1` (post detail) usually use (almost) all
columns, but `GET /posts` (post list) does not always use all columns
(e.g. use `id` and `title` for the list view, but `body` is not used).
If an association is eager loaded, the limited `select` doesn't works as
expected, eager loading will load all columns on the model, plus also
load the `select` columns additionally. It works differently with
natural load and preload. It means that changing natural load or preload
to eager load (or vice versa) is unsafe.
This fixes eager loading that always load all columns (plus extra
`select` columns), to respect the `select` columns like as others.
```ruby
post = Post.select("UPPER(title) AS title").first
post.title # => "WELCOME TO THE WEBLOG"
post.body # => ActiveModel::MissingAttributeError
# Rails 6.0 (ignore the `select` values)
post = Post.select("UPPER(title) AS title").eager_load(:comments).first
post.title # => "Welcome to the weblog"
post.body # => "Such a lovely day"
# Rails 6.1 (respect the `select` values)
post = Post.select("UPPER(title) AS title").eager_load(:comments).first
post.title # => "WELCOME TO THE WEBLOG"
post.body # => ActiveModel::MissingAttributeError
```
It is not a big issue for common types, since type casting in master
branch is much improved, but strictly speaking eager loading should
respect column types from database like as `find_by_sql` also does.
97c34a55fa/activerecord/lib/active_record/querying.rb (L46-L52)Fixes#39605.
Applying `includes` and `joins` to a relation that selected additional
database fields would cause those additional fields not to be included
in the results even though they were queried from the database:
posts = Post.select('1 as other').includes(:tbl).joins(:tbl)
posts.to_sql.include?('1 as other') #=> true
posts.first.attributes.include?('other') #=> false
This commit includes these additionally selected fields in the
instantiated results.