Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix total_count on loaded relation #932

Merged
merged 1 commit into from Dec 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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