ruby-on-railsapipaginationkaminarijbuilder

Rendering paginated pages in JBuilder views


I am currently paginating the return of a query attendees that has over 9000 items. My pages and routing work fine but I would like them to appear at the bottom of the page as clickable links to that page of the results. I am relatively new at using JBuilder I am using the Kaminari gem as well as the API-Pagination gem and would like to know how to I add visible/clickable page numbers to a JBuilder view according to Kaminari Docs <%= paginate @attendees %> is all that is needed. But as far as I understand JBuilder does not work or interpret that logic as its purely manufacturing JSON objects? Any advice is appreciated as well as a better explanation of what JBuilder is doing.

Controller

module Reports
  class ConferencesController < ::ApplicationController
    def attendees
      @conference = Conference.find(attendee_params[:conference_id])
      @attendees = @conference.attendees

      paginate json: @attendees, per_page: 500
    end

    private

    def attendee_params
      params.permit(:conference_id)
    end
  end
end
View
json.conference @conference, partial: 'conference', as: :conference
json.attendees @attendees, partial: 'attendee', as: :attendee


    <%= paginate @attendees %>


Solution

  • Kaminari works great of the box for HTML partials, but there are some additional things you need to do to set it up for other response formats. You can remove the paginate json: @attendees, per_page: 500 line from your controller in favor of something like

    @attendees = @conference.attendees.page(params[:page]).per(500)
    

    Additionally you will need to provide additional information to your jbuilder partial to render this information.

    Something like this:

    json.meta do
      json.total_pages @attendees.total_pages
      json.total_count @attendees.total_count
    end
    # See the Kaminari docs for more methods available https://github.com/kaminari/kaminari#the-page-scope