From 032ab94332fd5496c5af627bc36445cea3ba476a Mon Sep 17 00:00:00 2001 From: "Daniel E. Garcia Shulman" Date: Wed, 2 Nov 2016 21:45:54 +0200 Subject: Fixes TypeError Exception when cache counter value equals nil (#26940) * Fixes TypeError when cache counter value equals nil * Test case for counter cache on unloaded has_many association --- activerecord/lib/active_record/associations/has_many_association.rb | 2 +- activerecord/test/cases/associations/has_many_associations_test.rb | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index d1d0cc4c49..742cd25509 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -72,7 +72,7 @@ module ActiveRecord # the loaded flag is set to true as well. def count_records count = if reflection.has_cached_counter? - owner._read_attribute reflection.counter_cache_column + owner._read_attribute(reflection.counter_cache_column).to_i else scope.count end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 7eb04b1ffd..3afd062950 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1742,6 +1742,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert !company.clients.loaded? end + def test_counter_cache_on_unloaded_association + car = Car.create(name: "My AppliCar") + assert_equal car.engines.size, 0 + end + def test_get_ids_ignores_include_option assert_equal [readers(:michael_welcome).id], posts(:welcome).readers_with_person_ids end -- cgit v1.2.3