From 97d67908e28f9bff98e85c15dccfe7c542bbab88 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Mon, 14 Dec 2020 22:08:28 +0900 Subject: [PATCH] Fix `where` with aliased associations As the API doc shows, `alias_attribute` is designed to allow us to make aliases for *attributes*. https://api.rubyonrails.org/classes/ActiveModel/AttributeMethods/ClassMethods.html#method-i-alias_attribute However, coincidentally (and historically), `alias_attribute` also worked for associations. I've restored the behavior (it was lost in 56f3096) for the compatibility. Fixes #40832. --- activerecord/lib/active_record/relation/query_methods.rb | 5 ++++- activerecord/test/cases/relation/where_test.rb | 4 ++++ activerecord/test/models/comment.rb | 2 ++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 8e98aea255..54fe513304 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -1106,7 +1106,10 @@ module ActiveRecord when String, Array parts = [klass.sanitize_sql(rest.empty? ? opts : [opts, *rest])] when Hash - opts = opts.stringify_keys + opts = opts.transform_keys do |key| + key = key.to_s + klass.attribute_aliases[key] || key + end references = PredicateBuilder.references(opts) self.references_values |= references unless references.empty? diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb index 006008a663..98a1f68890 100644 --- a/activerecord/test/cases/relation/where_test.rb +++ b/activerecord/test/cases/relation/where_test.rb @@ -33,6 +33,10 @@ module ActiveRecord assert_equal [authors(:bob)], Author.joins(:categories).where(categories: categories(:technology)) end + def test_where_with_aliased_association + assert_equal [comments(:does_it_hurt)], Comment.where(entry: posts(:thinking)) + end + def test_type_cast_is_not_evaluated_at_relation_build_time posts = nil diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb index 21c328a24d..5fc7cef077 100644 --- a/activerecord/test/models/comment.rb +++ b/activerecord/test/models/comment.rb @@ -23,6 +23,8 @@ class Comment < ActiveRecord::Base has_many :children, class_name: "Comment", foreign_key: :parent_id, inverse_of: :parent belongs_to :parent, class_name: "Comment", counter_cache: :children_count, inverse_of: :children + alias_attribute :entry, :post + enum label: [:default, :child] class ::OopsError < RuntimeError; end