Skip to content

Commit

Permalink
Merge pull request #759 from faragorn/scopes-first
Browse files Browse the repository at this point in the history
Evaluate ransackable_scopes before attributes when building the query
  • Loading branch information
scarroll32 authored Mar 15, 2022
2 parents 0fcf1b5 + 9572540 commit bbd4b14
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/ransack/search.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ def build(params)
collapse_multiparameter_attributes!(params).each do |key, value|
if ['s'.freeze, 'sorts'.freeze].freeze.include?(key)
send("#{key}=", value)
elsif base.attribute_method?(key)
base.send("#{key}=", value)
elsif @context.ransackable_scope?(key, @context.object)
add_scope(key, value)
elsif base.attribute_method?(key)
base.send("#{key}=", value)
elsif !Ransack.options[:ignore_unknown_conditions] || !@ignore_unknown_conditions
raise ArgumentError, "Invalid search term #{key}"
end
Expand Down
23 changes: 23 additions & 0 deletions spec/ransack/search_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,29 @@ module Ransack
expect { Search.new(Person, params) }.not_to change { params }
end

context "ransackable_scope" do
around(:each) do |example|
Person.define_singleton_method(:name_eq) do |name|
self.where(name: name)
end

begin
example.run
ensure
Person.singleton_class.undef_method :name_eq
end
end

it "is prioritized over base predicates" do
allow(Person).to receive(:ransackable_scopes)
.and_return(Person.ransackable_scopes + [:name_eq])

s = Search.new(Person, name_eq: "Johny")
expect(s.instance_variable_get(:@scope_args)["name_eq"]).to eq("Johny")
expect(s.base[:name_eq]).to be_nil
end
end

end

describe '#result' do
Expand Down

0 comments on commit bbd4b14

Please sign in to comment.