File tree 3 files changed +39
-2
lines changed
3 files changed +39
-2
lines changed Original file line number Diff line number Diff line change @@ -42,6 +42,9 @@ def preload(associations, docs)
42
42
docs_map = { }
43
43
queue = [ klass . to_s ]
44
44
45
+ # account for single-collection inheritance
46
+ queue . push ( klass . root_class . to_s ) if klass != klass . root_class
47
+
45
48
while klass = queue . shift
46
49
if as = assoc_map . delete ( klass )
47
50
as . each do |assoc |
Original file line number Diff line number Diff line change @@ -44,6 +44,18 @@ def hereditary?
44
44
!!( superclass < Mongoid ::Document )
45
45
end
46
46
47
+ # Returns the root class of the STI tree that the current
48
+ # class participates in. If the class is not an STI subclass, this
49
+ # returns the class itself.
50
+ #
51
+ # @return [ Mongoid::Document ] the root of the STI tree
52
+ def root_class
53
+ root = self
54
+ root = root . superclass while root . hereditary?
55
+
56
+ root
57
+ end
58
+
47
59
# When inheriting, we want to copy the fields from the parent class and
48
60
# set the on the child to start, mimicking the behavior of the old
49
61
# class_inheritable_accessor that was deprecated in Rails edge.
Original file line number Diff line number Diff line change 15
15
Mongoid ::Contextual ::Mongo . new ( criteria )
16
16
end
17
17
18
+ let ( :association_host ) { Account }
19
+
18
20
let ( :inclusions ) do
19
21
includes . map do |key |
20
- Account . reflect_on_association ( key )
22
+ association_host . reflect_on_association ( key )
21
23
end
22
24
end
23
25
24
26
let ( :doc ) { criteria . first }
25
27
28
+ context 'when root is an STI subclass' do
29
+ # Driver has_one Vehicle
30
+ # Vehicle belongs_to Driver
31
+ # Truck is a Vehicle
32
+
33
+ before do
34
+ Driver . create! ( vehicle : Truck . new )
35
+ end
36
+
37
+ let ( :criteria ) { Truck . all }
38
+ let ( :includes ) { %i[ driver ] }
39
+ let ( :association_host ) { Truck }
40
+
41
+ it 'preloads the driver' do
42
+ expect ( doc . ivar ( :driver ) ) . to be false
43
+ context . preload ( inclusions , [ doc ] )
44
+ expect ( doc . ivar ( :driver ) ) . to be == Driver . first
45
+ end
46
+ end
47
+
26
48
context "when belongs_to" do
27
49
28
50
let! ( :account ) do
43
65
it "preloads the parent" do
44
66
expect ( doc . ivar ( :person ) ) . to be false
45
67
context . preload ( inclusions , [ doc ] )
46
- expect ( doc . ivar ( :person ) ) . to eq ( doc . person )
68
+ expect ( doc . ivar ( :person ) ) . to be == person
47
69
end
48
70
end
49
71
You can’t perform that action at this time.
0 commit comments