Skip to content

Commit

Permalink
Merge pull request #602 from martndemus/fix-alias-attribute-relations
Browse files Browse the repository at this point in the history
Fixes aliased attributes in association searches
  • Loading branch information
jonatack committed Dec 3, 2015
2 parents 5bd854e + d7b2520 commit 8e21298
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
4 changes: 2 additions & 2 deletions lib/ransack/nodes/bindable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ 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
end

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
Expand Down
20 changes: 15 additions & 5 deletions spec/ransack/adapters/active_record/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions spec/support/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 8e21298

Please sign in to comment.