Ticket #9734: has_many_through_size_use_counter_cache_r7675.diff
| File has_many_through_size_use_counter_cache_r7675.diff, 2.0 kB (added by xaviershay, 1 year ago) |
|---|
-
test/associations/join_model_test.rb
old new 457 457 assert !author.comments.loaded? 458 458 end 459 459 460 uses_mocha('has_many_through_collection_size_uses_counter_cache_if_it_exists') do 461 def test_has_many_through_collection_size_uses_counter_cache_if_it_exists 462 author = authors(:david) 463 author.stubs(:read_attribute).with('comments_count').returns(100) 464 assert_equal 100, author.comments.size 465 assert !author.comments.loaded? 466 end 467 end 468 460 469 def test_adding_junk_to_has_many_through_should_raise_type_mismatch 461 470 assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags << "Uhh what now?" } 462 471 end -
lib/active_record/associations/has_many_through_association.rb
old new 100 100 # calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero 101 101 # and you need to fetch that collection afterwards, it'll take one less SELECT query if you use length. 102 102 def size 103 loaded? ? @target.size : count 103 return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter? 104 return @target.size if loaded? 105 return count 104 106 end 105 107 106 108 # Calculate sum using SQL, not Enumerable … … 258 260 end 259 261 260 262 alias_method :sql_conditions, :conditions 263 264 def has_cached_counter? 265 @owner.attribute_present?(cached_counter_attribute_name) 266 end 267 268 def cached_counter_attribute_name 269 "#{@reflection.name}_count" 270 end 261 271 end 262 272 end 263 273 end