Will_paginate will report too many posts and pages

I use will_paginate to display the data returned from a query that includes both connections and the select statement. When I break pages into data, the number of records is equal to the number of records before executing the select statement, even though paginate is called after the query and the query contains fewer elements than page reports.

@sales = Sale.joins(:line_items).where(company_id: company_id, status: ['Complete', 'Voided'], time: (midnight_1..midnight_2)).order('id DESC') puts @sales.length 

14

 @sales = @sales.select('distinct sales.*') puts @sales.length 

4

 @sales.paginate(:per_page => 4, :page => params[page]) puts @sales.total_entries 

14

This leads to the display of links to blank pages.

+6
source share
2 answers

It will always be a little more difficult to paginate and join the has_many or has_and_belongs_to_many with will_paginate, or even any pagination solution.

If you do not need to request a federated link, you can delete it. You lose the advantage of getting related positions in one request, but you do not lose this.

If you need to request on it, and, presumably, you want sales to have only positions, you need to pass the count option: call paginate, which indicates the additional parameters that are used to call to calculate how many items are. In your case:

 @sales.paginate(:per_page => 4, :page => params[page], :count => {:group => 'sales.id' }) 
+10
source

Assuming your has_many: line_items sales model, joining you will get a "sales" entry for each associated "line_item".

+1
source

Source: https://habr.com/ru/post/916575/


All Articles