Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

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  
    457457    assert !author.comments.loaded? 
    458458  end 
    459459 
     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 
    460469  def test_adding_junk_to_has_many_through_should_raise_type_mismatch 
    461470    assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags << "Uhh what now?" } 
    462471  end 
  • lib/active_record/associations/has_many_through_association.rb

    old new  
    100100      # calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero 
    101101      # and you need to fetch that collection afterwards, it'll take one less SELECT query if you use length. 
    102102      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 
    104106      end 
    105107 
    106108      # Calculate sum using SQL, not Enumerable 
     
    258260        end 
    259261 
    260262        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 
    261271    end 
    262272  end 
    263273end