Skip to content

Commit

Permalink
Merge pull request #1225 from mhssmnn/allow-scopes-with-string-joins
Browse files Browse the repository at this point in the history
Allow scopes that define string SQL joins
  • Loading branch information
scarroll32 authored Mar 27, 2022
2 parents 3a0e520 + 1c69b9d commit be8c464
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/ransack/adapters/active_record/context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ def remove_association(association)
stashed.eql?(association)
}
@object.joins_values.delete_if { |jd|
jd.instance_variables.include?(:@join_root) &&
jd.instance_variable_get(:@join_root).children.map(&:object_id) == [association.object_id]
}
end
Expand Down
10 changes: 10 additions & 0 deletions spec/ransack/adapters/active_record/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ module ActiveRecord
expect(s.result.to_sql).to (include 'active = 1')
end

it 'applies scopes that define string SQL joins' do
allow(Article)
.to receive(:ransackable_scopes)
.and_return([:latest_comment_cont])

# Including a negative condition to test removing the scope
s = Search.new(Article, notes_note_not_eq: 'Test', latest_comment_cont: 'Test')
expect(s.result.to_sql).to include 'latest_comment'
end

context "with sanitize_custom_scope_booleans set to false" do
before(:all) do
Ransack.configure { |c| c.sanitize_custom_scope_booleans = false }
Expand Down
16 changes: 16 additions & 0 deletions spec/support/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,22 @@ class Article < ActiveRecord::Base
alias_attribute :content, :body

default_scope { where("'default_scope' = 'default_scope'") }
scope :latest_comment_cont, lambda { |msg|
join = <<-SQL
(LEFT OUTER JOIN (
SELECT
comments.*,
row_number() OVER (PARTITION BY comments.article_id ORDER BY comments.id DESC) AS rownum
FROM comments
) AS latest_comment
ON latest_comment.article_id = article.id
AND latest_comment.rownum = 1
)
SQL
.squish

joins(join).where("latest_comment.body ILIKE ?", "%#{msg}%")
}

ransacker :title_type, formatter: lambda { |tuples|
title, type = JSON.parse(tuples)
Expand Down

0 comments on commit be8c464

Please sign in to comment.