Skip to content
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

Allow scopes that define string SQL joins #1225

Merged
Merged
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
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