rails APIモードでlimitとoffsetのパラメータを渡す方法

実現したいこと

ページネーションを実装したいです。
フロントはreactで作っています。
APIを叩いてrailsでDBからデータを取得し、json形式でフロントに返すようにしたいです。

前提

単純にコントローラーの書き方がわかりません。
どのように書けばいいのか教えてください。

該当のソースコード

Contoller

rails

12before_action :test_param, only: %i[test_index] 3 4 def test_index 5 posts = Post.order(created_at: "DESC").limit(limit_params).offset(offset_params) 6 render json: posts 7 end 8 9 def test_param 10 limit_params = params[:limit]&.to_i 11 offset_params = params[:offset]&.to_i 12 end 13

route.rb

get 'posts/test_index/:limit/:offset', to:'posts#test_index'

試したこと

上記の通りですができなかったです。
500エラーとなります。
理想としては、たとえば以下のカールコマンドたたいた時
postsテーブルから、3~5件目を取り出せるようにしたいです。

curl -i localhost:XXXX/posts/test_index/3/2

補足情報(FW/ツールのバージョンなど)

rails
APIモード

コメントを投稿

0 コメント