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

Rails 6.1中如何获取修改格式后的当前请求路径?

Rails 6.1中安全替换PDF请求路径为HTML路径的标准方法

直接用request.fullpath.sub(".pdf", "")确实有风险,会误替换路径中间的.pdf字符串(比如/files/invoice.pdf/history.pdf会被改成/files/invoice/history.pdf,不符合预期)。推荐以下几种更标准的实现方式:

方法1:正则精准替换末尾的.pdf扩展名

通过正则匹配路径末尾的.pdf(包含可能的查询参数),确保只替换目标扩展名:

html_fullpath = request.fullpath.sub(/\.pdf(\?.*)?$/, '\1')
  • 正则说明:\.pdf(\?.*)?$匹配字符串末尾的.pdf,后面可以跟查询参数(?xxx);替换时保留查询参数部分(\1),如果没有查询参数则直接去掉.pdf。

方法2:调用路由辅助方法(推荐)

如果你的PDF请求对应明确的HTML路由,直接使用Rails生成的路由辅助方法是最规范的做法,完全避免手动路径处理的问题:
比如你的PDF路由定义是:

# config/routes.rb
get '/reports/:id', to: 'reports#show', format: :pdf
get '/reports/:id', to: 'reports#show', format: :html # 或默认format为html

那么在控制器中可以直接生成HTML路径并重定向:

redirect_to report_path(params[:id], format: :html)
# 或者省略format,因为默认通常是html
redirect_to report_path(params[:id])

方法3:拆分路径和扩展名处理

通过文件操作方法拆分路径的扩展名和目录部分,再重新组合:

# 拆分路径的目录、文件名和扩展名
dir_path = File.dirname(request.path)
base_name = File.basename(request.path, '.pdf')
# 重新组合路径,保留原查询参数
html_path = File.join(dir_path, base_name)
html_fullpath = request.query_string.present? ? "#{html_path}?#{request.query_string}" : html_path

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:05:00