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地址即可。
方案二:手动修复参数与补全方法
如果不想依赖第三方分支,也可以自己动手解决:
修复参数转换错误
报错的核心原因是will_paginate在生成链接时,直接传递了未经过参数许可的Ransack查询参数(通常是q参数)。你可以在生成分页链接时,先对参数做许可处理:# 在你的视图或自定义辅助方法中 def paginate_with_ransack(collection) will_paginate collection, params: params.permit(:page, q: {}) end这样就能避免未许可参数无法转成hash的问题。
补全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

