You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mongoid实现ROR分页时total_pages方法未定义问题求助

Fixing the 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 your Gemfile
  • Run bundle install if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 17:13:09