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

Rails 7中带参数的路由路径失效问题求助

问题场景

将Rails 5应用升级到Rails 7后,使用link_to传递临时参数时出现报错。原路由声明如下:

resources :recording_sets do
  member do
    get 'export'
  end
  collection do
    get 'about'
  end
end

在Rails 5中,可通过以下方式传递参数:

link_to('Recordings', recording_sets_path(:kind=>1))

控制器中获取参数的逻辑:

def index
  if params[:kind]
    @recording_sets = RecordingSet.where('kind = ?', params[:kind]).where(visibility_limitation)
    @kind = params[:kind]
  else
    @recording_sets = RecordingSet.all.where(visibility_limitation)
    @kind = false
  end

  respond_to do |format|
    if @kind.to_s == "1" # Record
      format.html { render action: "index_records" }
    else
      format.html
    end
    format.json { render json: @recording_sets }
  end
end

Rails 7中的报错信息

undefined method `map' for #<ActionDispatch::Journey::Formatter::RouteWithParams:0x00000001121e2270 ...>

super(route_key, options, recall).map(&:dup)
                                 ^^^^
Did you mean?  tap

尝试过的无效方案

  • 修改resource声明添加param: :kind:
resources :recording_sets, param: :kind do
  member do
    get 'export'
  end
  collection do
    get 'about'
  end
end
  • 单独声明带路径参数的GET路由:
get 'recording_sets/:kind/', to: 'recording_sets#index'

执行rails routes显示路由已生成,但问题仍存在:

GET      /recording_sets/:kind(.:format)    recording_sets#index

正确解决方案

问题根源在于Rails 7对路径辅助方法的参数处理更严格:

  1. 无需修改原有路由:kind是可选的过滤参数,作为查询参数传递即可,不需要在路由中定义路径参数。
  2. 修正link_to写法:直接传递参数,Rails会自动将其转为查询参数:
link_to('Recordings', recording_sets_path(kind: 1))

生成的URL为/recording_sets?kind=1,控制器中params[:kind]的获取逻辑无需修改。

如果一定要将kind作为路径参数,需调整路由优先级并处理无参数的场景,但这种方案会破坏原有集合路由的可用性,不推荐。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:27:32