Search code examples
ruby-on-rails-4kaminariactive-model-serializersjson-api

page[size] getting updated from 10 to 1 when user lands on a page with only 1 result


#app/serializers/admin_serializer.rb
class AdminSerializer < ActiveModel::Serializer
  attributes :id, :email, :access_locked?
end


#app/controllers/dashboard/admins_controller.rb
def index
    @search = Admin.search(params[:q])
    if params[:page]
      @admins = @search.result(:distinct => true).page(params[:page][:number]).per(params[:page][:size])
    else
      @admins = @search.result(:distinct => true).page(1).per(10)
    end
    respond_to do |format|
      format.html
      format.json {render json: @admins}
    end
end

On accessing http://dashboard.localhost.com:3000/admins.json I am getting correct links, with page[size] param as 10. The subsequent page has only one admin object to show

"links": {
    "self": "http://dashboard.localhost.com:3000/admins.json?page%5Bnumber%5D=1&page%5Bsize%5D=10",
    "next": "http://dashboard.localhost.com:3000/admins.json?page%5Bnumber%5D=2&page%5Bsize%5D=10",
    "last": "http://dashboard.localhost.com:3000/admins.json?page%5Bnumber%5D=5&page%5Bsize%5D=10"
  }

But if I access the last link here i.e. http://dashboard.localhost.com:3000/admins.json?page%5Bnumber%5D=5&page%5Bsize%5D=10 The subsequent JSON cotains the following incorrect links, with page[size] param as 1. Since this page has only one admin object to show, all the other links thus generated contains page[size]=1

"links": {
    "self": "http://dashboard.localhost.com:3000/admins.json?page%5Bnumber%5D=5&page%5Bsize%5D=10",
    "first": "http://dashboard.localhost.com:3000/admins.json?page%5Bnumber%5D=1&page%5Bsize%5D=10",
    "prev": "http://dashboard.localhost.com:3000/admins.json?page%5Bnumber%5D=4&page%5Bsize%5D=10"
  }

Solution

  • Fixed this by replacing the @admins = @search.result(:distinct => true).page(params[:page][:number]).per(params[:page][:size]) by @admins = @search.result(:distinct => true).page(params[:page][:number]).per(10)