From ad04b1c6d73358c3254a75e3f489997103f41b56 Mon Sep 17 00:00:00 2001 From: classicalliu Date: Thu, 12 Jul 2018 11:31:42 +0800 Subject: [PATCH] add offset and limit support to controller index action --- app/controllers/api/blocks_controller.rb | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/app/controllers/api/blocks_controller.rb b/app/controllers/api/blocks_controller.rb index 773b321..81051b2 100644 --- a/app/controllers/api/blocks_controller.rb +++ b/app/controllers/api/blocks_controller.rb @@ -7,6 +7,10 @@ class Api::BlocksController < ApplicationController # "transactionTo": "max transaction count", // integer # "page": "1", // default 1 # "perPage": "10", // default 10 + # + # # offset and limit has lower priority than page and perPage + # "offset": "1", // database offset for pagination + # "limit": "10", //database limit for pagination # } # GET /api/blocks def index @@ -17,10 +21,20 @@ def index transaction_count_lteq: parse_hex(params[:transactionTo]) } - blocks = Block.ransack(options).result.order(block_number: :desc).page(params[:page]).per(params[:perPage]) + blocks = Block.ransack(options).result.order(block_number: :desc) + + if params[:page].nil? && !params[:offset].nil? + # use offset and limit + total_count = blocks.count + blocks = blocks.offset(params[:offset]).limit(params[:limit]) + else + # use page and perPage + blocks = blocks.page(params[:page]).per(params[:perPage]) + total_count = blocks.total_count + end render json: { - count: blocks.total_count, + count: total_count, blocks: ActiveModelSerializers::SerializableResource.new(blocks, each_serializer: ::Api::BlockSerializer) } end