diff --git a/lib/ransack/search.rb b/lib/ransack/search.rb index b8c1ab6c..95980c0c 100644 --- a/lib/ransack/search.rb +++ b/lib/ransack/search.rb @@ -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 diff --git a/spec/ransack/search_spec.rb b/spec/ransack/search_spec.rb index c5003164..6426a20a 100644 --- a/spec/ransack/search_spec.rb +++ b/spec/ransack/search_spec.rb @@ -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