Created
          September 5, 2013 04:18 
        
      - 
      
 - 
        
Save be9/6446051 to your computer and use it in GitHub Desktop.  
    kaminari + JSON API pagination helper
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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 | 
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
Where is that file supposed to be? is it a helper?
For Rails + Jbuilder :
In your resource index ( users for example ) :
app/views/users/index.json.jbuilder
.
.
json.partial! "shared/pagination", collection: @usersapp/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
endNice script.
Thanks!
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
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Awesome! Works perfectly with a Rails 5.1 + Webapacker + Vue app, thanks!