页面[大小]当用户登陆只有1个结果的页面时,从10更新到1

时间:2016-03-29 12:24:28

标签: ruby-on-rails-4 kaminari active-model-serializers json-api

#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

访问http://dashboard.localhost.com:3000/admins.json时,我收到了正确的链接,page[size] param为10.后续页面只有一个管理对象可供展示

"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"
  }

但如果我在这里访问最后一个链接,http://dashboard.localhost.com:3000/admins.json?page%5Bnumber%5D=5&page%5Bsize%5D=10 随后的JSON包含以下错误链接,page[size] param为1.由于此页面只显示一个管理对象,因此生成的所有其他链接包含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"
  }

1 个答案:

答案 0 :(得分:0)

通过替换来解决这个问题 @admins = @search.result(:distinct => true).page(params[:page][:number]).per(params[:page][:size])的{​​{1}}