feat: 広場のページネーション(#169) (#189)

#169 バグ修正

Merge remote-tracking branch 'origin/main' into feature/169

#169

Co-authored-by: miteruzo <miteruzo@naver.com>
Reviewed-on: #189
This commit was merged in pull request #189.
This commit is contained in:
2025-12-30 11:13:03 +09:00
parent 0344b61557
commit d224ccef4c
2 changed files with 52 additions and 23 deletions
+25 -10
View File
@@ -3,20 +3,35 @@ class PostsController < ApplicationController
# GET /posts
def index
limit = params[:limit].presence&.to_i
page = (params[:page].presence || 1).to_i
limit = (params[:limit].presence || 20).to_i
cursor = params[:cursor].presence
created_at = ('COALESCE(posts.original_created_before - INTERVAL 1 SECOND,' +
'posts.original_created_from,' +
'posts.created_at)')
q = filtered_posts.order(Arel.sql("#{ created_at } DESC"))
q = q.where("#{ created_at } < ?", Time.iso8601(cursor)) if cursor
page = 1 if page < 1
limit = 1 if limit < 1
posts = limit ? q.limit(limit + 1) : q
offset = (page - 1) * limit
sort_sql =
'COALESCE(posts.original_created_before - INTERVAL 1 SECOND,' +
'posts.original_created_from,' +
'posts.created_at)'
q =
filtered_posts
.preload(:tags)
.with_attached_thumbnail
.select("posts.*, #{ sort_sql } AS sort_ts")
.order(Arel.sql("#{ sort_sql } DESC"))
posts = (
if cursor
q.where("#{ sort_sql } < ?", Time.iso8601(cursor)).limit(limit + 1)
else
q.limit(limit).offset(offset)
end).to_a
next_cursor = nil
if limit && posts.size > limit
next_cursor = posts.last.created_at.iso8601(6)
if cursor && posts.length > limit
next_cursor = posts.last.read_attribute('sort_ts').iso8601(6)
posts = posts.first(limit)
end
@@ -29,7 +44,7 @@ class PostsController < ApplicationController
nil
end
end
}, next_cursor: }
}, count: filtered_posts.count(:id), next_cursor: }
end
def random