Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will_paginate generates wrong number of page links

I am Using will paginate 3.0.2 and Rails 3.1.0.

The following code lives within my controller.

  @users = User.visible_for(current_user).
           includes(:study_courses).
           ordered_by_last_name.
           page(params[:page]).per_page(20)

In a partial where @users has been assigned with users from above I do:

= will_paginate users, previous_label: h("<"), next_label: h(">") 

If there are 20 Users it gives me 6 page links, where the first page contains 20 users, the second page contains 10 users and of course the remaining pages contain zero users.

I can not figure out why there are 6 page links generated instead of 3.

UPDATE: Figured out that will_paginate does not use distinct to count the records. Any ideas how to do this?

like image 939
NilsHaldenwang Avatar asked Dec 28 '22 12:12

NilsHaldenwang


2 Answers

OK, I found a solution on my own:

  user_count = User.visible_for(current_user).count(distinct: true)
  @users = User.visible_for(current_user).
                includes(:study_courses).
                ordered_by_last_name.
                paginate(page: params[:page],
                         per_page: 20,
                         total_entries: user_count)

In my scope I use disctinct, but calling count on the relation seems to overwrite that. So one has to count by hand and pass the count into the paginate method.

like image 89
NilsHaldenwang Avatar answered Jan 06 '23 03:01

NilsHaldenwang


This way looks cleaner: https://stackoverflow.com/a/10740732/2599681

I tried it and works nicely with Rails 3.2.11 and WillPaginate 3.0.4.

Regards!

like image 27
jdiezf Avatar answered Jan 06 '23 02:01

jdiezf