Skip to content

Commit 1109829

Browse files
riseshiascarroll32Copilot
authored
Check all children of Arel::Nodes::And to extract correlated key (#1572)
* Add test for correct join key extraction with more than 2 conditions on join * Check all children of Arel::Nodes::And to extract correlated key * Make test mysql compatible * Update spec/support/schema.rb Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Sean <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent e830390 commit 1109829

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

lib/ransack/adapters/active_record/context.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,12 @@ def extract_correlated_key(join_root)
202202
nil
203203
end
204204
when Arel::Nodes::And
205-
extract_correlated_key(join_root.left) || extract_correlated_key(join_root.right)
205+
# And may have multiple children, so we need to check all, not via left/right
206+
join_root.children.each do |child|
207+
key = extract_correlated_key(child)
208+
return key if key
209+
end
210+
nil
206211
else
207212
# eg parent was Arel::Nodes::And and the evaluated side was one of
208213
# Arel::Nodes::Grouping or MultiTenant::TenantEnforcementClause

spec/ransack/adapters/active_record/context_spec.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,25 @@ module ActiveRecord
9797

9898
expect(search.result.to_sql).to match /.comments.\..person_id. = .people.\..id./
9999
end
100+
101+
it 'build correlated subquery for polymorphic & default_scope when predicate is not_cont_all' do
102+
search = Search.new(Article,
103+
g: [
104+
{
105+
m: "and",
106+
c: [
107+
{
108+
a: ["recent_notes_note"],
109+
p: "not_eq",
110+
v: ["some_note"],
111+
}
112+
]
113+
}
114+
],
115+
)
116+
117+
expect(search.result.to_sql).to match /(.notes.\..note. != \'some_note\')/
118+
end
100119
end
101120

102121
describe 'sharing context across searches' do

spec/support/schema.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ class Article < ApplicationRecord
176176
has_many :comments
177177
has_and_belongs_to_many :tags
178178
has_many :notes, as: :notable
179+
has_many :recent_notes, as: :notable
179180

180181
alias_attribute :content, :body
181182

@@ -257,6 +258,14 @@ class Note < ApplicationRecord
257258
belongs_to :notable, polymorphic: true
258259
end
259260

261+
class RecentNote < ApplicationRecord
262+
DEFAULT_NOTABLE_ID = 1
263+
self.table_name = "notes"
264+
default_scope { where(notable_id: DEFAULT_NOTABLE_ID) }
265+
266+
belongs_to :notable, polymorphic: true
267+
end
268+
260269
class Account < ApplicationRecord
261270
belongs_to :agent_account, class_name: "Account"
262271
belongs_to :trade_account, class_name: "Account"

0 commit comments

Comments
 (0)