Skip to content
7 changes: 6 additions & 1 deletion lib/ransack/adapters/active_record/context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,12 @@ def extract_correlated_key(join_root)
nil
end
when Arel::Nodes::And
extract_correlated_key(join_root.left) || extract_correlated_key(join_root.right)
# And may have multiple children, so we need to check all, not via left/right
join_root.children.each do |child|
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@riseshia what is the potential for performance issues here?

Copy link
Contributor Author

@riseshia riseshia Sep 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no performance issue here, it just has possibility that join_root have more than 2 children.

key = extract_correlated_key(child)
return key if key
end
nil
else
# eg parent was Arel::Nodes::And and the evaluated side was one of
# Arel::Nodes::Grouping or MultiTenant::TenantEnforcementClause
Expand Down
19 changes: 19 additions & 0 deletions spec/ransack/adapters/active_record/context_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,25 @@ module ActiveRecord

expect(search.result.to_sql).to match /.comments.\..person_id. = .people.\..id./
end

it 'build correlated subquery for polymorphic & default_scope when predicate is not_cont_all' do
search = Search.new(Article,
g: [
{
m: "and",
c: [
{
a: ["recent_notes_note"],
p: "not_eq",
v: ["some_note"],
}
]
}
],
)

expect(search.result.to_sql).to match /(.notes.\..note. != \'some_note\')/
end
end

describe 'sharing context across searches' do
Expand Down
9 changes: 9 additions & 0 deletions spec/support/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ class Article < ApplicationRecord
has_many :comments
has_and_belongs_to_many :tags
has_many :notes, as: :notable
has_many :recent_notes, as: :notable

alias_attribute :content, :body

Expand Down Expand Up @@ -257,6 +258,14 @@ class Note < ApplicationRecord
belongs_to :notable, polymorphic: true
end

class RecentNote < ApplicationRecord
DEFAULT_NOTABLE_ID = 1
self.table_name = "notes"
default_scope { where(notable_id: DEFAULT_NOTABLE_ID) }

belongs_to :notable, polymorphic: true
end

class Account < ApplicationRecord
belongs_to :agent_account, class_name: "Account"
belongs_to :trade_account, class_name: "Account"
Expand Down
Loading