CodexBloom - Programming Q&A Platform

Rails 7.1: How to handle custom query scopes with pagination using Kaminari and ActiveRecord?

👀 Views: 83 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
ruby-on-rails pagination kaminari active-record Ruby

I'm building a Ruby on Rails application (version 7.1) and I'm trying to implement pagination for a custom scope in my ActiveRecord model. I have a scope that filters users based on their status and I want to paginate the results. However, when I apply pagination using Kaminari, I'm getting an behavior that says `undefined method 'total_pages' for ActiveRecord::Relation:Class`. Here's what my code looks like: ```ruby class User < ApplicationRecord scope :active, -> { where(status: 'active') } end ``` In my controller, I'm doing the following: ```ruby class UsersController < ApplicationController def index @users = User.active.page(params[:page]).per(10) end end ``` I also have Kaminari set up, as I've added it to my Gemfile: ```ruby gem 'kaminari' ``` And I've run `bundle install`. However, the pagination doesn't seem to work as expected. I've confirmed that I have the Kaminari initializer set up properly and I can see the `page` method in my console when I inspect `User.active`. However, when I call the `page` method, it returns an `ActiveRecord::Relation`, but it seems like it's not being recognized as a valid query for pagination. I've tried to troubleshoot by checking the logs, but I don't see any SQL queries being executed for pagination. I also ensured that my `Kaminari` version is compatible with Rails 7.1, as I have `kaminari (1.2.1)` installed. Can anyone provide insight into why I'm working with this scenario and how to properly paginate a custom scope in Rails using Kaminari? Any advice on best practices for this scenario would also be appreciated. My development environment is Windows. I'd really appreciate any guidance on this.