public
Description: Ruby on Rails
Homepage: http://rubyonrails.org
Clone URL: git://github.com/rails/rails.git
Search Repo:
Make size for has_many :through use counter cache if it exists.  Closes 
#9734 [xaviershay]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@7692 
5ecf4fe2-1ee6-0310-87b1-e25e094e27de
technoweenie (author)
Sat Sep 29 23:47:20 -0700 2007
commit  30a652ad41428b922b1ed637f491776f1f1dff13
tree    e20a92f14f88e6c5c9a46631fb1b744cb6356a3a
parent  e5a60fb2bfe0c15c297af88c19690788b00109d0
...
1
2
 
 
3
4
5
...
1
2
3
4
5
6
7
0
@@ -1,5 +1,7 @@
0
 *2.0.0 [Preview Release]* (September 29th, 2007) [Includes duplicates of changes from 1.14.2 - 1.15.3]
0
 
0
+* Make size for has_many :through use counter cache if it exists. Closes #9734 [xaviershay]
0
+
0
 * Remove DB2 adapter since IBM chooses to maintain their own adapter instead. [Jeremy Kemper]
0
 
0
 * Extract Oracle, SQLServer, and Sybase adapters into gems. [Jeremy Kemper]
...
100
101
102
103
 
 
 
104
105
106
...
258
259
260
 
 
 
 
 
 
 
 
261
262
263
...
100
101
102
 
103
104
105
106
107
108
...
260
261
262
263
264
265
266
267
268
269
270
271
272
273
0
@@ -100,7 +100,9 @@
0
       # calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero
0
       # and you need to fetch that collection afterwards, it'll take one less SELECT query if you use length.
0
       def size
0
- loaded? ? @target.size : count
0
+ return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter?
0
+ return @target.size if loaded?
0
+ return count
0
       end
0
 
0
       # Calculate sum using SQL, not Enumerable
0
@@ -258,6 +260,14 @@
0
         end
0
 
0
         alias_method :sql_conditions, :conditions
0
+
0
+ def has_cached_counter?
0
+ @owner.attribute_present?(cached_counter_attribute_name)
0
+ end
0
+
0
+ def cached_counter_attribute_name
0
+ "#{@reflection.name}_count"
0
+ end
0
     end
0
   end
0
 end
...
457
458
459
 
 
 
 
 
 
 
 
 
460
461
462
...
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
0
@@ -457,6 +457,15 @@
0
     assert !author.comments.loaded?
0
   end
0
 
0
+ uses_mocha('has_many_through_collection_size_uses_counter_cache_if_it_exists') do
0
+ def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
0
+ author = authors(:david)
0
+ author.stubs(:read_attribute).with('comments_count').returns(100)
0
+ assert_equal 100, author.comments.size
0
+ assert !author.comments.loaded?
0
+ end
0
+ end
0
+
0
   def test_adding_junk_to_has_many_through_should_raise_type_mismatch
0
     assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags << "Uhh what now?" }
0
   end

Comments

    No one has commented yet.