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

Rails 5.2中will_paginate与Ransack联用参数错误求解决方案

解决Rails 5.2中will_paginate与ransack的兼容问题

我之前也踩过这个Rails 5.2下will_paginate和ransack搭配的坑,折腾了好一阵,整理了几个亲测有效的解决方案,分享给你:

方案一:使用社区适配的will_paginate分支

Ransack官方的will_paginate分支确实存在page_entries_info缺失的问题,不过社区里已经有开发者fork并修复了这个问题——不仅解决了unable to convert unpermitted parameters to hash的参数转换错误,还补全了page_entries_info方法的实现。你可以在GitHub上搜索关键词「will_paginate ransack rails 5.2」找到这类仓库,然后替换Gemfile中的will_paginate引用为该fork地址即可。

方案二:手动修复参数与补全方法

如果不想依赖第三方分支,也可以自己动手解决:

  1. 修复参数转换错误
    报错的核心原因是will_paginate在生成链接时,直接传递了未经过参数许可的Ransack查询参数(通常是q参数)。你可以在生成分页链接时,先对参数做许可处理:

    # 在你的视图或自定义辅助方法中
    def paginate_with_ransack(collection)
      will_paginate collection, params: params.permit(:page, q: {})
    end
    

    这样就能避免未许可参数无法转成hash的问题。

  2. 补全page_entries_info方法
    你可以从官方will_paginate的源码中复制page_entries_info的实现,粘贴到项目的app/helpers/application_helper.rb中,然后稍微调整以适配Ransack返回的集合类型。比如官方的基础实现大概是这样:

    def page_entries_info(collection, options = {})
      entry_name = options[:entry_name] || (collection.empty? ? 'entry' : collection.first.class.name.underscore)
    
      if collection.total_pages < 2
        case collection.size
        when 0 then "No #{entry_name.pluralize} found"
        when 1 then "Showing <b>1</b> #{entry_name}"
        else "Showing <b>all #{collection.size}</b> #{entry_name.pluralize}"
        end
      else
        start = (collection.current_page - 1) * collection.per_page + 1
        finish = [start + collection.per_page - 1, collection.total_count].min
        "Showing <b>#{start}–#{finish}</b> of <b>#{collection.total_count}</b> #{entry_name.pluralize}"
      end.html_safe
    end
    

    这个方法能直接适配Ransack返回的ActiveRecord::Relation集合,解决数组相关错误。

方案三:临时替代page_entries_info

如果不想复制源码,也可以快速实现一个简化版的替代方法:

def custom_page_entries_info(collection)
  total = collection.total_count
  per_page = collection.per_page
  current_page = collection.current_page
  start = (current_page - 1) * per_page + 1
  finish = [start + per_page - 1, total].min
  "Showing #{start} to #{finish} of #{total} entries"
end

这个方法足够满足大部分场景的分页信息显示需求。

另外,如果你愿意贡献力量的话,非常建议你把自己的解决方案整理后提交PR到官方仓库,或者发布自己的fork分享给社区——这对后续遇到同样问题的开发者会有很大帮助!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:18:58