total_count for a loaded Relation that has no @_per can also be calculable using `default_per_page`

Default per_page for a loaded Relation that has no @_per is `default_per_page`
This commit is contained in:
Akira Matsuda 2017-01-05 01:16:39 +09:00
parent 11d4aaf3ed
commit c5aca2f5a2
2 changed files with 8 additions and 1 deletions

View File

@ -21,7 +21,8 @@ module Kaminari
# Total count has to be 0 if loaded records are 0
return @total_count = 0 if (current_page == 1) && @records.empty?
# Total count is calculatable at the last page
return @total_count = (current_page - 1) * @_per + @records.length if @records.any? && defined?(@_per) && (@records.length < @_per)
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)
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

View File

@ -21,15 +21,21 @@ if defined? ActiveRecord
end
test 'total_count on not yet loaded Relation' do
assert_equal 0, User.where('1 = 0').page(1).total_count
assert_equal 0, User.where('1 = 0').page(1).per(10).total_count
assert_equal 7, User.page(1).total_count
assert_equal 7, User.page(1).per(10).total_count
assert_equal 7, User.page(2).total_count
assert_equal 7, User.page(2).per(10).total_count
assert_equal 7, User.page(2).per(2).total_count
end
test 'total_count on loded 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
end