使用Mongoid实现ROR分页时total_pages方法未定义问题求助
undefined method 'total_pages' Error with mongoid-pagination Let's break down why you're hitting this error and how to fix it step by step:
The Root Cause
Your current controller code only calls per_page(10) without specifying a page number via the page() method. The mongoid-pagination gem requires both methods to be chained onto your query to generate a paginated collection that includes the necessary metadata (like total_pages) that the paginate helper relies on.
Step 1: Update Your Controller Code
Modify your controller to include the page() method, which uses the params[:page] value from the request (this defaults to page 1 if no parameter is provided):
@services = Service.where(active: true).page(params[:page]).per_page(10)
Step 2: Verify Gem Setup
Double-check that you've properly set up the gem:
- Ensure
gem 'mongoid-pagination'is added to yourGemfile - Run
bundle installif you haven't already - Restart your Rails server to make sure the gem loads correctly
Bonus: Compatibility Note
If you're using a newer version of Mongoid (7.x+), keep in mind that mongoid-pagination hasn't been updated in quite some time. If you still run into issues after the above fix, consider switching to actively maintained alternatives like kaminari-mongoid or will_paginate-mongoid—they offer similar functionality with better support for modern Mongoid versions.
Test the Fix
After updating the controller code, reload your index page. The paginate helper should now have access to the total_pages method and render pagination links correctly.
内容的提问来源于stack exchange,提问作者Carlos lima

