From d7b2520a83e3f8ff8df854ee5dc221d1411d77a5 Mon Sep 17 00:00:00 2001 From: Marten Schilstra Date: Tue, 6 Oct 2015 09:48:39 +0200 Subject: [PATCH] Fixes aliased attributes in association searches --- lib/ransack/nodes/bindable.rb | 4 ++-- .../adapters/active_record/base_spec.rb | 20 ++++++++++++++----- spec/support/schema.rb | 2 ++ 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/lib/ransack/nodes/bindable.rb b/lib/ransack/nodes/bindable.rb index 72bb17887..4615df1d8 100644 --- a/lib/ransack/nodes/bindable.rb +++ b/lib/ransack/nodes/bindable.rb @@ -37,7 +37,7 @@ def get_arel_attribute def get_attribute if is_alias_attribute? - context.table_for(parent)[context.klass.attribute_aliases[attr_name]] + context.table_for(parent)[parent.base_klass.attribute_aliases[attr_name]] else context.table_for(parent)[attr_name] end @@ -45,7 +45,7 @@ def get_attribute def is_alias_attribute? Ransack::SUPPORTS_ATTRIBUTE_ALIAS && - context.klass.attribute_aliases.key?(attr_name) + parent.base_klass.attribute_aliases.key?(attr_name) end end end diff --git a/spec/ransack/adapters/active_record/base_spec.rb b/spec/ransack/adapters/active_record/base_spec.rb index 9420464b8..9a9038cc8 100644 --- a/spec/ransack/adapters/active_record/base_spec.rb +++ b/spec/ransack/adapters/active_record/base_spec.rb @@ -274,12 +274,22 @@ def self.simple_escaping? expect(s.result.to_a).to eq [p] end - it 'should translate attribute aliased column names', + context 'attribute aliased column names', if: Ransack::SUPPORTS_ATTRIBUTE_ALIAS do - s = Person.ransack(full_name_eq: 'Nicolas Cage') - expect(s.result.to_sql).to match( - /WHERE #{quote_table_name("people")}.#{quote_column_name("name")}/ - ) + it 'should be translated to original column name' do + s = Person.ransack(full_name_eq: 'Nicolas Cage') + expect(s.result.to_sql).to match( + /WHERE #{quote_table_name("people")}.#{quote_column_name("name")}/ + ) + end + + it 'should translate on associations' do + s = Person.ransack(articles_content_cont: 'Nicolas Cage') + expect(s.result.to_sql).to match( + /#{quote_table_name("articles")}.#{ + quote_column_name("body")} I?LIKE '%Nicolas Cage%'/ + ) + end end it 'allows sort by `only_sort` field' do diff --git a/spec/support/schema.rb b/spec/support/schema.rb index 97235de15..b05d4607c 100644 --- a/spec/support/schema.rb +++ b/spec/support/schema.rb @@ -113,6 +113,8 @@ class Article < ActiveRecord::Base has_and_belongs_to_many :tags has_many :notes, as: :notable + alias_attribute :content, :body + if ActiveRecord::VERSION::STRING >= '3.1' default_scope { where("'default_scope' = 'default_scope'") } else # Rails 3.0 does not accept a block