@@ -72,7 +72,7 @@ def join_details_by_relationship(relationship)
72
72
@join_details [ segment ]
73
73
end
74
74
75
- def self . get_join_arel_node ( records , options = { } )
75
+ def self . get_join_arel_node ( records , relationship , join_type , options = { } )
76
76
init_join_sources = records . arel . join_sources
77
77
init_join_sources_length = init_join_sources . length
78
78
@@ -82,9 +82,27 @@ def self.get_join_arel_node(records, options = {})
82
82
if join_sources . length > init_join_sources_length
83
83
last_join = ( join_sources - init_join_sources ) . last
84
84
else
85
+ # Try to find a pre-existing join for this table.
86
+ # We can get here if include_optional_linkage_data is true
87
+ # (or always_include_to_xxx_linkage_data),
88
+ # and the user's custom `records` method has already added that join.
89
+ #
90
+ # If we want a left join and there is already an inner/left join,
91
+ # then we can use that.
92
+ # If we want an inner join and there is alrady an inner join,
93
+ # then we can use that (but not a left join, since that doesn't filter things out).
94
+ valid_join_types = [ Arel ::Nodes ::InnerJoin ]
95
+ valid_join_types << Arel ::Nodes ::OuterJoin if join_type == :left
96
+ table_name = relationship . resource_klass . _table_name
97
+
98
+ last_join = join_sources . find { |j |
99
+ valid_join_types . any? { |t | j . is_a? ( t ) } && j . left . name == table_name
100
+ }
101
+ end
102
+
103
+ if last_join . nil?
85
104
# :nocov:
86
105
warn "get_join_arel_node: No join added"
87
- last_join = nil
88
106
# :nocov:
89
107
end
90
108
@@ -162,7 +180,7 @@ def perform_joins(records, options)
162
180
next
163
181
end
164
182
165
- records , join_node = self . class . get_join_arel_node ( records , options ) { |records , options |
183
+ records , join_node = self . class . get_join_arel_node ( records , relationship , join_type , options ) { |records , options |
166
184
related_resource_klass . join_relationship (
167
185
records : records ,
168
186
resource_type : related_resource_klass . _type ,
0 commit comments