Skip to content

Instantly share code, notes, and snippets.

@penguinwokrs
Created August 29, 2018 11:18
Show Gist options
  • Save penguinwokrs/45a7cfed3c31698da9b3e2409d83cffe to your computer and use it in GitHub Desktop.
Save penguinwokrs/45a7cfed3c31698da9b3e2409d83cffe to your computer and use it in GitHub Desktop.
ページネーションよりcursor型の実装
# frozen_string_literal: true
class AlterContentIdColumns < ActiveRecord::Migration[5.1]
def change
[
:contents,
:products
].each do |table|
add_column table, :uuid, :'CHAR(26)', unique: true, index: true, after: :id
end
end
end
# sortable uuid
gem 'ulid', require: false
# frozen_string_literal: true
require_dependency 'api/v1/application_controller'
module Api
module V1
module Timeline
module Paginatable
extend ActiveSupport::Concern
# pagination
# FIXME: 再利用性があるように書き換える。
def cursor_paginate(klass, cursor: nil)
last_page = klass.last&.uuid
klass = klass.where("`uuid` < '#{cursor}'") if cursor.present?
klass = klass.limit(20)
@next_page = klass.last&.uuid
response.headers['Link'] = last_page != @next_page && !@next_page.nil? ? "page=#{@next_page}" : ''
klass
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment