Skip to content

Check all children of Arel::Nodes::And to extract correlated key #1572

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -201,7 +201,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|
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 include '("notes"."note" != \'some_note\')'
end
end

describe 'sharing context across searches' do
Expand Down
8 changes: 8 additions & 0 deletions spec/support/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,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 @@ -246,6 +247,13 @@ class Note < ApplicationRecord
belongs_to :notable, polymorphic: true
end

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

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