Skip to content

Commit

Permalink
Merge pull request #932 from tumayun/master
Browse files Browse the repository at this point in the history
Fix total_count on loaded relation
  • Loading branch information
yuki24 committed Dec 21, 2017
2 parents 2afce63 + 59a550e commit 4ada38c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
Expand Up @@ -21,8 +21,7 @@ def total_count(column_name = :all, _options = nil) #:nodoc:
# Total count has to be 0 if loaded records are 0
return @total_count = 0 if (current_page == 1) && @records.empty?
# Total count is calculable at the last page
per_page = (defined?(@_per) && @_per) || default_per_page
return @total_count = (current_page - 1) * per_page + @records.length if @records.any? && (@records.length < per_page)
return @total_count = (current_page - 1) * limit_value + @records.length if @records.any? && (@records.length < limit_value)
end

# #count overrides the #select which could include generated columns referenced in #order, so skip #order here, where it's irrelevant to the result anyway
Expand Down
Expand Up @@ -30,14 +30,20 @@ class ActiveRecordRelationMethodsTest < ActiveSupport::TestCase
assert_equal 7, User.page(2).per(2).total_count
end

test 'total_count on loded Relation' do
test 'total_count on loaded Relation' do
assert_equal 0, User.where('1 = 0').page(1).load.total_count
assert_equal 0, User.where('1 = 0').page(1).per(10).load.total_count
assert_equal 7, User.page(1).load.total_count
assert_equal 7, User.page(1).per(10).load.total_count
assert_equal 7, User.page(2).load.total_count
assert_equal 7, User.page(2).per(10).load.total_count
assert_equal 7, User.page(2).per(2).load.total_count

old_max_per_page = User.max_per_page
User.max_paginates_per(5)
assert_equal 7, User.page(1).per(100).load.total_count
assert_equal 7, User.page(2).per(100).load.total_count
User.max_paginates_per(old_max_per_page)
end

test 'it should reset total_count memoization when the scope is cloned' do
Expand Down

0 comments on commit 4ada38c

Please sign in to comment.