1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
Commit graph

7 commits

Author SHA1 Message Date
Ryuta Kamizono
4639318215 Fix eager loading that non-select columns will be loaded
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
```
2020-08-17 12:05:43 +09:00
Ryuta Kamizono
090ec3daaf Type cast extra select for eager loading
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.
2020-07-07 15:41:33 +09:00
Patrick Rebsch
2d6088ced5 Retain selections with includes and joins
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.
2019-12-03 20:45:12 -05:00
Abhay Nikam
82b0ff03b1 Fixed reselect throwing NoMethodError on ActiveRecord. 2019-03-03 22:25:10 +05:30
Willian Gustavo Veiga
00c50c2b59 Add reselect method 2018-08-13 22:19:39 -03:00
Kazuhiro Sera
52919f3d13 Fix the obvious typos detected by github.com/client9/misspell 2018-08-08 21:55:46 +09:00
Mohsen Alizadeh
ccbba22938 add test case to relation select 2017-12-03 15:16:52 +03:30