@@ -72,7 +72,7 @@ def join_details_by_relationship(relationship)
7272 @join_details [ segment ]
7373 end
7474
75- def self . get_join_arel_node ( records , options = { } )
75+ def self . get_join_arel_node ( records , relationship , join_type , options = { } )
7676 init_join_sources = records . arel . join_sources
7777 init_join_sources_length = init_join_sources . length
7878
@@ -82,9 +82,27 @@ def self.get_join_arel_node(records, options = {})
8282 if join_sources . length > init_join_sources_length
8383 last_join = ( join_sources - init_join_sources ) . last
8484 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?
85104 # :nocov:
86105 warn "get_join_arel_node: No join added"
87- last_join = nil
88106 # :nocov:
89107 end
90108
@@ -162,7 +180,7 @@ def perform_joins(records, options)
162180 next
163181 end
164182
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 |
166184 related_resource_klass . join_relationship (
167185 records : records ,
168186 resource_type : related_resource_klass . _type ,
0 commit comments