ruby-on-railspaginationwill-paginate

Add pagination count to the same GET response in Rails API


I can achieve the same thing, but in multiple commands. Is there any way to combine them and render API response in one GET request?

List all records in this page:

render json: Apartment.paginate(page: 1, per_page: 20)

Get total pages:

render json: Apartment.paginate(page: 1, per_page: 20).total_pages

Get total entries:

render json: Apartment.paginate(page: 1, per_page: 20).total_entries

Happy with any method: combine the response, overwrite the response or even add counts to each record.

Many thanks!


Solution

  • you can send all 3 commands in a single json response, then all your data is in one object.

    @apartments = Apartment.paginate(page: 1, per_page: 20)
    render json: {apartments: @apartments, 
                 total_pages: @apartments.total_pages, 
                 total_entries: @apartments.total_entries }