Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
kaminari + JSON API pagination helper
def paginate(scope, default_per_page = 20)
collection = scope.page(params[:page]).per((params[:per_page] || default_per_page).to_i)
current, total, per_page = collection.current_page, collection.num_pages, collection.limit_value
return [{
pagination: {
current: current,
previous: (current > 1 ? (current - 1) : nil),
next: (current == total ? nil : (current + 1)),
per_page: per_page,
pages: total,
count: collection.total_count
}
}, collection]
end
@gbarillot
Copy link

gbarillot commented Dec 7, 2017

Awesome! Works perfectly with a Rails 5.1 + Webapacker + Vue app, thanks!

@hechien
Copy link

hechien commented Apr 13, 2018

Hi, thanks for the share, but there's something need to be updated.

The collection.num_pages should be changed to collection.total_pages.

Please reference: https://github.com/kaminari/kaminari/releases/tag/v1.0.0.beta1

@dbarrionuevo
Copy link

dbarrionuevo commented Jan 16, 2019

Where is that file supposed to be? is it a helper?

@AhmedKamal20
Copy link

AhmedKamal20 commented Feb 28, 2019

For Rails + Jbuilder :

In your resource index ( users for example ) :

app/views/users/index.json.jbuilder

.
.
json.partial! "shared/pagination", collection: @users

app/views/shared/_pagination.json.jbuilder

json.pagination do
  current, total, per_page = collection.current_page, collection.total_pages, collection.limit_value
  json.current  current
  json.previous (current > 1 ? (current - 1) : nil)
  json.next     (current == total ? nil : (current + 1))
  json.per_page per_page
  json.pages    total
  json.count    collection.total_count
end

@fernandommota
Copy link

fernandommota commented Jun 25, 2019

Nice script.

Thanks!

@azmatrana
Copy link

azmatrana commented Apr 10, 2020

In addition to the @AhmedKamal20 answer above.

Its better to use the pre given methods by kaminari gem for all the values. Also, in my case I also need the data as well so also added that as well in the pagination.

app/views/shared/_pagination.json.jbuilder

json.pagination do
  json.current         collection.current_page
  json.previous        collection.prev_page
  json.next            collection.next_page
  json.limit           collection.limit_value
  json.total_pages     collection.total_pages
  json.total_count     collection.total_count

  json.data            collection # if want to send the data as well. In my case I am sending data. 
end

@glinda93
Copy link

glinda93 commented Apr 24, 2021

Hi, thanks for the share, but there's something need to be updated.

The collection.num_pages should be changed to collection.total_pages.

Please reference: https://github.com/kaminari/kaminari/releases/tag/v1.0.0.beta1

🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment