Created
August 29, 2018 11:18
-
-
Save penguinwokrs/45a7cfed3c31698da9b3e2409d83cffe to your computer and use it in GitHub Desktop.
ページネーションよりcursor型の実装
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# sortable uuid | |
gem 'ulid', require: false |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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