Allow scopes that define string SQL joins

This commit is contained in:
Mark Haussmann 2021-05-12 13:19:04 +12:00
parent b627a386d7
commit 43fa042eee
3 changed files with 27 additions and 0 deletions

View File

@ -139,6 +139,7 @@ module Ransack
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

View File

@ -78,6 +78,16 @@ module Ransack
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 }

View File

@ -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}%")
}
end
class StoryArticle < Article