activerecord_scoped_includes 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3ac5b6dd0abbbee28197e833e5529e24ed4be9484d03ef1aff33587d73ca73d4
4
- data.tar.gz: 1336aa9325d5adc2b4e76a49fe623da50deedbd5b0fb187ed7d486b9077e8913
3
+ metadata.gz: fd5ce3f76da4890e536222e595b9d13d48b8eb9cf7b667c3b307a3ef2320e96d
4
+ data.tar.gz: 6d3a7c09c3238a061f88fe1db100c8cfa7091c566546b2ca107d97833219866f
5
5
  SHA512:
6
- metadata.gz: a1f0352a9f9922b0ecc8d7c7e24552616817fda52794eab359b480b0aca70292df77dd7b3e5b04d37876567189c102464082e34b48ba32fbc95f23769bfe3f7d
7
- data.tar.gz: 070a74e8e79985c297d250630558a40327025122e9c92717ff9715b026fe4ed7691443bbf64c65d5178fedd9a2a71edce1377c0320f3784ff64419b39e38664a
6
+ metadata.gz: 648092316f7d20d5111b4860c47ce1a0537beaea1982ac0dc77c818a63ae72bce0adcbe1a5f2bfc3877d1de774fb1abd6484075b2665139ecd2c5ababa4a1045
7
+ data.tar.gz: 056ca16361857887a59e2a7e58311f549dddd1d3d6ad1c21758c06f0df73ae1755099f781ccb2560e63d15f98bbb9c49a7ee0bbe7b69185bf565c9910f8b7bd4
data/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.2 (2026-11-25)
4
+
5
+ - Load the associations included inside a lambda, which were ignored and then loaded lazily.
6
+ - Add the keys that nested associations need to scopes that select columns, such as the foreign key of a `belongs_to`.
7
+
3
8
  ## 0.0.1 (2026-11-18)
4
9
 
5
10
  - Initial release: a scope as the value of an association in `includes`, `preload` and `eager_load`, as a lambda or a relation.
data/README.md CHANGED
@@ -11,9 +11,8 @@ Scoped Includes
11
11
  [mongoid_includes]: https://github.com/ElMassimo/mongoid_includes
12
12
  [nested_select]: https://github.com/alekseyl/nested_select
13
13
  [Sequel]: https://sequel.jeremyevans.net/rdoc/files/doc/advanced_associations_rdoc.html
14
- [Issues]: https://github.com/ElMassimo/activerecord_scoped_includes/issues
15
14
 
16
- Choose the columns an [Active Record] association loads, right where you include it.
15
+ Customize which columns are loaded when eager loading [Active Record] associations.
17
16
 
18
17
  ```ruby
19
18
  Album.includes(songs: -> { select(:id, :name) })
@@ -21,11 +20,10 @@ Album.includes(songs: -> { select(:id, :name) })
21
20
  # SELECT "songs"."id", "songs"."name", "songs"."album_id" FROM "songs" WHERE "songs"."album_id" IN (1, 2)
22
21
  ```
23
22
 
24
- The records load into the association itself, so `album.songs` has them, and code that reads it doesn't need to know which columns were loaded or under which name.
25
-
26
23
  ## Why? 🤔
27
24
 
28
- To load an association with different columns, Rails needs another association:
25
+ Selecting different columns when loading an association usually means defining
26
+ another association:
29
27
 
30
28
  ```ruby
31
29
  class Album < ApplicationRecord
@@ -34,18 +32,20 @@ class Album < ApplicationRecord
34
32
  end
35
33
  ```
36
34
 
37
- Each variant needs a name, and the code that reads the records has to pick the right one. When a page loads one variant and a component reads the other, the same records are loaded twice.
35
+ This becomes cumbersome when different pages need different columns, and it's
36
+ easy to preload `song_titles` only to have a serializer call `songs`, loading
37
+ the records again.
38
38
 
39
- This library lets the query decide how the association is loaded, in the same `includes` call that loads it.
39
+ With Scoped Includes, you can select columns in the `includes` call and keep
40
+ using `album.songs`, without defining extra associations.
40
41
 
41
42
  ## Features ⚡️
42
43
 
43
- - A scope as the value of an association, in `includes`, `preload` and `eager_load`
44
- - Accepts a lambda, as in association scopes, or a relation
45
- - Nested includes go inside the scope, so each association keeps its own shape
46
- - Adds the keys that link records to their owners, which a `select` can easily leave out
47
- - Works with `has_many :through`, `belongs_to`, `strict_loading` and `Preloader`
48
- - Works with [deferred_columns], to opt into deferred columns per association
44
+ - Customize `includes`, `preload` and `eager_load` with a lambda or relation
45
+ - Select columns independently for nested associations
46
+ - Automatically selects the keys required to load associations
47
+ - Supports `has_many :through`, `belongs_to`, `strict_loading` and `Preloader`
48
+ - Load deferred columns per association when using [deferred_columns]
49
49
 
50
50
  ## Installation 💿
51
51
 
@@ -63,14 +63,15 @@ And then run:
63
63
 
64
64
  ### Selecting columns
65
65
 
66
- Pass a scope as the value of an association:
66
+ You can pass a lambda or an Active Record relation to select columns for an association:
67
67
 
68
68
  ```ruby
69
69
  Album.includes(songs: -> { select(:name, :track) })
70
70
  Album.preload(songs: Song.select(:name, :track))
71
71
  ```
72
72
 
73
- A lambda is evaluated on the associated model, like an association scope, while a relation can be built anywhere and reused:
73
+ Lambdas are evaluated on the associated model, just like association scopes.
74
+ You can also reuse a relation:
74
75
 
75
76
  ```ruby
76
77
  SONG_TITLES = Song.select(:name, :track)
@@ -78,40 +79,50 @@ SONG_TITLES = Song.select(:name, :track)
78
79
  Album.includes(songs: SONG_TITLES)
79
80
  ```
80
81
 
81
- It works the same with `eager_load`, and with `includes` when it eager loads:
82
+ This also works with `eager_load`, or when `includes` uses a join:
82
83
 
83
84
  ```ruby
84
85
  Album.eager_load(songs: -> { select(:name) })
85
86
  Album.includes(songs: -> { select(:name) }).where(songs: { track: 1..3 })
86
87
  ```
87
88
 
88
- When eager loading, the scope can only select columns of the table, so `select("UPPER(name) AS name")` raises an `ArgumentError`.
89
+ When loading through a join, you can only select columns from the associated
90
+ table. SQL expressions such as `select("UPPER(name) AS name")` raise an `ArgumentError`.
89
91
 
90
- ### Keys
92
+ ### Primary and foreign keys
91
93
 
92
- A select doesn't need to list the keys that link each record to its owner, such as `album_id` above.
94
+ You don't need to include primary and foreign keys in your `select`. Scoped
95
+ Includes adds the keys Active Record needs to load the association, such as
96
+ `id` and `album_id` in the first example.
93
97
 
94
- In plain Rails, leaving them out of an association scope loads no records, without raising. This library adds them to the select.
98
+ Without this, omitting the foreign key when preloading a `has_many` association
99
+ can leave it empty, without raising an error.
95
100
 
96
- ### Nesting includes
101
+ ### Nested associations
97
102
 
98
- Include associations of the scoped association inside the scope:
103
+ To load nested associations, call `includes` on the relation or inside the lambda:
99
104
 
100
105
  ```ruby
101
106
  Artist.includes(albums: Album.select(:name).includes(songs: -> { select(:name) }))
107
+ Artist.includes(albums: -> { select(:name).includes(songs: -> { select(:name) }) })
102
108
  ```
103
109
 
104
- Associations without a scope can be mixed in as usual:
110
+ The keys that nested associations need are selected as well, such as
111
+ `album_id` in `Song.select(:name).includes(:album)`.
112
+
113
+ You can combine this with regular includes:
105
114
 
106
115
  ```ruby
107
116
  Song.includes(:playlist_entries, album: -> { select(:name) })
108
117
  ```
109
118
 
110
- ### Only the shape, not the records
119
+ ### Filtering and sorting
111
120
 
112
- A scope can select columns, include associations, and enable `strict_loading`.
121
+ Scopes in `includes` support selecting columns, loading nested associations,
122
+ and enabling `strict_loading`, but not filtering, sorting, or limiting records.
113
123
 
114
- It can't filter or sort the records, since the association would then hold only some of its records, and other code reading it would get a partial list:
124
+ For example, using `where` would leave `album.songs` with only some of its songs,
125
+ which could surprise other code using the association:
115
126
 
116
127
  ```ruby
117
128
  Album.includes(songs: -> { where(track: 1) })
@@ -119,7 +130,7 @@ Album.includes(songs: -> { where(track: 1) })
119
130
  # To load only some of the records, define an association with that scope instead.
120
131
  ```
121
132
 
122
- Define an association for those instead, as usual:
133
+ If you need to filter or sort records, define a separate association:
123
134
 
124
135
  ```ruby
125
136
  has_many :opening_tracks, -> { where(track: 1) }, class_name: "Song"
@@ -127,29 +138,37 @@ has_many :opening_tracks, -> { where(track: 1) }, class_name: "Song"
127
138
 
128
139
  ### With deferred_columns
129
140
 
130
- The scope can opt into the columns that [deferred_columns] leaves out:
141
+ If you are using [deferred_columns], you can load deferred columns with `with_deferred`:
131
142
 
132
143
  ```ruby
133
144
  Album.includes(songs: -> { with_deferred(:lyrics) })
134
145
  ```
135
146
 
136
- This loads the lyrics into `album.songs`, instead of a separate `songs_with_lyrics` association. The opt-ins add up with those of the association scope:
147
+ This makes `lyrics` available when accessing `album.songs`.
148
+
149
+ If the association already uses `with_deferred`, the additional columns are
150
+ loaded along with those specified in the association:
137
151
 
138
152
  ```ruby
139
153
  Album.eager_load(songs_with_lyrics: -> { with_deferred(:waveform) }) # lyrics and waveform
140
154
  ```
141
155
 
142
- ### Associations that are already loaded
156
+ ### Already loaded associations
143
157
 
144
- Like Rails, the preloader keeps the records of an association that is already loaded, so their columns stay as they were.
158
+ As with regular preloading, associations that are already loaded are not reloaded.
159
+ Passing a scope won't fetch additional columns for those records.
145
160
 
146
161
  ## How it works 🔧
147
162
 
148
- `includes` and `preload` build a tree of associations with `Preloader::Branch`. When the value of an association is a scope, its nested includes become the children of the branch, and the rest of the scope is merged into the scope of the loader, the same way `Preloader.new(scope:)` applies a scope to every association.
163
+ For `preload` and `includes` without joins, the library extends
164
+ `Preloader::Branch` to accept a scope per association. Nested includes become
165
+ child branches, and the scope is merged with the association's loading scope.
149
166
 
150
- `eager_load` builds a `JoinDependency` instead, which selects the column names of each joined model. When the association has a scope, those are the columns its `SELECT` would list, so selects and opt-ins from other libraries apply as well.
167
+ For `eager_load` and `includes` with joins, it extends `JoinDependency` to use
168
+ the columns selected by each scope instead of all columns from the joined table.
151
169
 
152
- Both are private APIs of Active Record, so the library is tested against every supported version, including `main`.
170
+ These are private Active Record APIs. The test suite runs against all supported
171
+ versions, including Rails `main`.
153
172
 
154
173
  ## Compatibility
155
174
 
@@ -164,7 +183,8 @@ bundle install
164
183
  bin/rspec
165
184
  ```
166
185
 
167
- Some tests check that it works along with [deferred_columns]. They use a checkout in a sibling folder (`../deferred_columns`) when there's one, and the released gem otherwise.
186
+ Integration tests with [deferred_columns] use a local checkout at
187
+ `../deferred_columns` if available, or the released gem otherwise.
168
188
 
169
189
  To run the tests against a specific version of Rails, set `BUNDLE_GEMFILE` to one of the files in `gemfiles`:
170
190
 
@@ -32,7 +32,8 @@ module ActiveRecord
32
32
  end
33
33
 
34
34
  # The columns of the association scope merged with the includes scope, as
35
- # its SELECT would list them, plus the primary key to tell records apart.
35
+ # its SELECT would list them, plus the primary key to tell records apart,
36
+ # and the keys that the associations it includes need.
36
37
  def column_names
37
38
  includes_scope ? includes_column_names : super
38
39
  end
@@ -42,7 +43,8 @@ module ActiveRecord
42
43
  def includes_column_names
43
44
  @includes_column_names ||= begin
44
45
  scope = reflection.scope ? reflection.scope_for(base_klass.unscoped).merge(includes_scope) : includes_scope
45
- scope.arel.projections.flat_map { |projection| projected_columns(projection) } | [base_klass.primary_key]
46
+ keys = [*base_klass.primary_key, *ScopedIncludes.owner_keys(children.map(&:reflection))]
47
+ scope.arel.projections.flat_map { |projection| projected_columns(projection) } | keys
46
48
  end
47
49
  end
48
50
 
@@ -59,6 +61,17 @@ module ActiveRecord
59
61
  private
60
62
 
61
63
  def build(associations, base_klass)
64
+ associations.each do |name, children|
65
+ scope = children.instance_variable_get(:@includes_scope)
66
+ reflection = find_reflection(base_klass, name)
67
+ next unless scope.is_a?(Proc) && !reflection.polymorphic?
68
+
69
+ # A lambda is only resolved once the model is known, to nest its includes.
70
+ scope = ScopedIncludes.resolve(scope, reflection.klass)
71
+ children.instance_variable_set(:@includes_scope, scope)
72
+ self.class.walk_tree(ScopedIncludes.nested(scope), children)
73
+ end
74
+
62
75
  super.each_with_index do |join, index|
63
76
  scope = associations.values[index].instance_variable_get(:@includes_scope)
64
77
  join.includes_scope = ScopedIncludes.resolve(scope, join.base_klass) if scope
@@ -19,7 +19,7 @@ module ActiveRecord
19
19
  return super unless @includes_scope && @includes_reflection
20
20
 
21
21
  (@includes_scopes ||= {})[@includes_reflection] ||= begin
22
- scope = ScopedIncludes.resolve(@includes_scope, @includes_reflection.klass).except(:includes, :preload, :eager_load)
22
+ scope = shape_of(resolved_includes_scope(@includes_reflection.klass))
23
23
  preload_scope = super
24
24
  if preload_scope.is_a?(ActiveRecord::Relation)
25
25
  preload_scope.merge(scope)
@@ -31,11 +31,36 @@ module ActiveRecord
31
31
  end
32
32
  end
33
33
 
34
+ # A lambda is only resolved once the model is known, so the associations it
35
+ # includes become children when its records are about to load.
36
+ def children
37
+ return super unless @includes_scope.is_a?(Proc) && @loaders && !@nested
38
+
39
+ @nested = true
40
+ @includes_reflection = nil # so that the children get the scope of the preloader
41
+ @children = build_children(@resolved_includes_scopes.to_h.values.flat_map { |scope| ScopedIncludes.nested(scope) })
42
+ end
43
+
34
44
  # Remembers the reflection, since each target model resolves the scope separately.
35
45
  def preloaders_for_reflection(reflection, records)
36
46
  @includes_reflection = reflection
37
47
  super
38
48
  end
49
+
50
+ private
51
+
52
+ def resolved_includes_scope(model)
53
+ (@resolved_includes_scopes ||= {})[model] ||= ScopedIncludes.resolve(@includes_scope, model)
54
+ end
55
+
56
+ # The scope without its includes, selecting the keys they need to load.
57
+ def shape_of(scope)
58
+ names = ScopedIncludes.nested(scope).flat_map { |nested| nested.is_a?(Hash) ? nested.keys : nested }
59
+ keys = ScopedIncludes.owner_keys(names.filter_map { |name| scope.klass._reflect_on_association(name) })
60
+ keys -= scope.select_values.map(&:to_s)
61
+ scope = scope.except(:includes, :preload, :eager_load)
62
+ scope.select_values.any? && keys.any? ? scope.select(*keys) : scope
63
+ end
39
64
  end
40
65
 
41
66
  # Loads the records of an association.
@@ -2,6 +2,6 @@
2
2
 
3
3
  module ActiveRecord
4
4
  module ScopedIncludes
5
- VERSION = '0.0.1'
5
+ VERSION = '0.0.2'
6
6
  end
7
7
  end
@@ -40,6 +40,16 @@ module ActiveRecord
40
40
 
41
41
  [*scope.includes_values, *scope.preload_values, *scope.eager_load_values]
42
42
  end
43
+
44
+ # The columns of their owner that the associations need to load their records,
45
+ # such as the foreign key of a `belongs_to`.
46
+ def self.owner_keys(reflections)
47
+ reflections.flat_map { |reflection|
48
+ link = reflection
49
+ link = link.through_reflection while link.through_reflection?
50
+ link.belongs_to? ? [*link.foreign_key, *(link.foreign_type if link.polymorphic?)] : [*link.active_record_primary_key]
51
+ }.map(&:to_s).uniq
52
+ end
43
53
  end
44
54
  end
45
55
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: activerecord_scoped_includes
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
4
+ version: 0.0.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Maximo Mussini