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

Rails 6搭配Kaminari分页出现undefined method `/` for String报错如何解决?

报错原因
  • params中获取的page/limit参数如果传递了空值(比如请求参数为?page=),此时params[:page]的值为空字符串而非nil,现有逻辑不会触发|| 1的默认值兜底,直接将字符串类型的值传入Kaminari的分页方法。
  • Kaminari内部计算分页偏移量时需要对页码、每页数量做数值除法运算,字符串类型没有/方法,因此抛出对应错误。
修复方案
  1. 调整PaginationHelper中分页参数的获取逻辑,强制将参数转换为整数,同时对非法值做兜底处理:
module PaginationHelper
  def paginate!(collection)
    collection.page(current_page).per(current_limit)
  end

  def current_page
    page = params[:page].to_i
    # 空字符串、负数、0都默认返回第一页
    page.positive? ? page : 1
  end

  def current_limit
    limit = params[:limit].to_i
    # 限制每页查询数量的上下限,避免一次性查询大量数据拖垮服务,可按业务需求调整上限
    limit.between?(1, 100) ? limit : 100
  end
end
  1. 补充调用分页方法:现有TestController的index动作没有调用paginate!方法,分页逻辑不会生效,需要调整为:
class TestController < ApplicationController
  def index
    @collection = paginate!(current_account.test_items)
  end
end

内容的提问来源于stack exchange,提问作者dennismonsewicz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:18:01