diff --git a/activerecord/lib/active_record/association_relation.rb b/activerecord/lib/active_record/association_relation.rb index ef9650d482..45f1b07f69 100644 --- a/activerecord/lib/active_record/association_relation.rb +++ b/activerecord/lib/active_record/association_relation.rb @@ -17,6 +17,10 @@ module ActiveRecord @association.empty? end + def ==(other) + other == to_a + end + private def exec_queries diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 4adc8a3862..709edbee88 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -569,7 +569,7 @@ module ActiveRecord # Compares two relations for equality. def ==(other) case other - when Associations::CollectionProxy + when Associations::CollectionProxy, AssociationRelation self == other.to_a when Relation other.to_sql == to_sql diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index d253b94b10..b428605b9d 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -568,6 +568,15 @@ class BasicsTest < ActiveRecord::TestCase assert Bulb.where(car_id: car.id) == car.bulbs.to_a, 'Relation should be comparable with Array' end + def test_equality_of_relation_and_association_relation + car = Car.create! + car.bulbs.build + car.save + + assert_equal Bulb.where(car_id: car.id), car.bulbs.includes(:car), 'Relation should be comparable with AssociationRelation' + assert_equal car.bulbs.includes(:car), Bulb.where(car_id: car.id), 'AssociationRelation should be comparable with Relation' + end + def test_hashing assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ] end