From e1320db168cec34a96ae66b97ef42229e3fda181 Mon Sep 17 00:00:00 2001 From: =?utf-8?q?Tarmo=20T=C3=A4nav?= Date: Tue, 26 Aug 2008 19:29:16 +0300 Subject: [PATCH] Implement count limit/offset support for has_many associations --- .../associations/has_many_association.rb | 11 ++++++++++- .../associations/has_many_associations_test.rb | 6 ++++++ 2 files changed, 16 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index ce62127..1535995 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -14,7 +14,16 @@ module ActiveRecord @finder_sql + " AND (#{sanitize_sql(options[:conditions])})" options[:include] ||= @reflection.options[:include] - @reflection.klass.count(column_name, options) + value = @reflection.klass.count(column_name, options) + + limit = @reflection.options[:limit] + offset = @reflection.options[:offset] + + if limit || offset + [ [value - offset.to_i, 0].max, limit.to_i ].min + else + value + end end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index da3c8fb..17fd88c 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -48,6 +48,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 2, Firm.find(:first).plain_clients.count(:name) end + def test_counting_with_association_limit + firm = companies(:first_firm) + assert_equal firm.limited_clients.length, firm.limited_clients.size + assert_equal firm.limited_clients.length, firm.limited_clients.count + end + def test_finding assert_equal 2, Firm.find(:first).clients.length end -- 1.6.0