Uday kumar das
Uday kumar das

Reputation: 1613

total_entries for will_paginate not working properly rails 4

In controller:

@top_holders = Holders.where(:client_id=>1).paginate(:page => params[:page],:per_page => 10 ,:total_entries => 12)

In view:

<%= will_paginate @top_holders, renderer: BootstrapPagination::Rails %>

In the view page i am getting 20 records which is incorrect, it should be 12 records. i.e In page=1 it returns 10 records and in page=2 it returns another 10 records.

For getting a solution i have lost a whole day, please help me out.

Upvotes: 2

Views: 2483

Answers (4)

elyalvarado
elyalvarado

Reputation: 1296

The total_entries option just is a shortcut to avoid will_paginate querying the count for the results, that's why you're getting additional results in your last page. So if you really want to limit the number of results shown in will paginate, but not mess up with the pagination results you'll need to use a subquery (because will_paginate will overwrite any limit you set):

@top_holders = Holders.
  where(
    id: Holders.where(client_id: 1).limit(12).map(&:id)
  ).paginate(page: params[:page], per_page: 10)

However, this might cause issues if instead of 12 you want to show a very large number of holders because you might hit the query length limit in some databases.

Upvotes: 0

Rafael Porras Lucena
Rafael Porras Lucena

Reputation: 76

if total_entries is being used just to save the SQL COUNT query... why do you want to return less results than the existing ones?

If you really needed you could do this:

PAGE_SIZE = 15
MAX_SIZE = 70

per_page = if PAGE_SIZE * params[:page] > MAX_SIZE
  MAX_SIZE - (MAX_SIZE / PAGE_SIZE) * PAGE_SIZE
else
  PAGE_SIZE
end

@top_holders = Holders.where(client_id: 1).paginate(page: params[:page], per_page: per_page)

Upvotes: 0

soltex
soltex

Reputation: 3551

Your query is probably not returning only 12 records, I would try another approach using limit, something like this:

@top_holders = Holders.where(:client_id=>1).paginate(:page => params[:page],:per_page => 10).limit(12)

limit(N) will give you the last N records

Upvotes: 1

tlehman
tlehman

Reputation: 5167

The total_entries key is just a way to avoid a SQL COUNT query. Set the :per_page to a higher value if you want more results returned.

Upvotes: 1

Related Questions