56

I am using rails 3.2. I am paginating my results using .page(1).per_page(10)

like

@users = User.method().page(1).per_page(10)

Now how to find the total count of the users from the pagination

As because @users.count gives 10 from the first page and not the total count

How to get the total count of the users even after pagination

EDIT : @users.total_count gives the whole paginated count

useranon
  • 29,318
  • 31
  • 98
  • 146

3 Answers3

101

As mentioned in the question, you can get the total count of the records with

@users.total_count

I've added this as an answer for the sake of completeness.

Jon Cairns
  • 11,783
  • 4
  • 39
  • 66
1

You can use @users.total_count.

However, if you're trying to get the total count for each page, i.e. something like:

20 of 135 results

then total_count will just return 135, not the number of results on the page.

If you want to handle this case as well as the case where the number of results is less than the pagination result number, then I'd go with something like this:

(per_size > @users.total_count) ? @users.total_count : per_size

where per_size is the value you are setting for your per scope (docs here).

DaniG2k
  • 4,772
  • 36
  • 77
0

User.count would give you the count but it would hit the db. If you are using mongodb @user.length would give you the total count

Abhay Kumar
  • 1,582
  • 1
  • 19
  • 45