Skip to content

Commit 367942d

Browse files
tarmojeremy
authored andcommitted
Implement count limit/offset support for has_many associations
[#348 state:resolved] Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
1 parent 0ed29df commit 367942d

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

activerecord/lib/active_record/associations/has_many_association.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,16 @@ def count(*args)
1414
@finder_sql + " AND (#{sanitize_sql(options[:conditions])})"
1515
options[:include] ||= @reflection.options[:include]
1616

17-
@reflection.klass.count(column_name, options)
17+
value = @reflection.klass.count(column_name, options)
18+
19+
limit = @reflection.options[:limit]
20+
offset = @reflection.options[:offset]
21+
22+
if limit || offset
23+
[ [value - offset.to_i, 0].max, limit.to_i ].min
24+
else
25+
value
26+
end
1827
end
1928
end
2029

activerecord/test/cases/associations/has_many_associations_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ def test_counting_with_column_name_and_hash
4848
assert_equal 2, Firm.find(:first).plain_clients.count(:name)
4949
end
5050

51+
def test_counting_with_association_limit
52+
firm = companies(:first_firm)
53+
assert_equal firm.limited_clients.length, firm.limited_clients.size
54+
assert_equal firm.limited_clients.length, firm.limited_clients.count
55+
end
56+
5157
def test_finding
5258
assert_equal 2, Firm.find(:first).clients.length
5359
end

0 commit comments

Comments
 (0)