Search code examples
ruby-on-rails-3will-paginate

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?


Solution

  • 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.