Rails- redirect_to 携带不需要的 ID

Rails- redirect_to carrying over unwanted id

我正在尝试从显示操作重定向到自定义收集操作,但 id 参数被保留,导致路由失败。一个最小的例子:

routes.rb:

resources :first_models, only: [:show]

resources :second_models do
  get 'custom_action', on: :collection
end

first_models_controller.rb

class FirstModelsController < ApplicationController
  def show
    redirect_to controller: 'SecondModelsController', action: 'custom_action'
  end
end

second_models_controller.rb

class SecondModelsController < ApplicationController
  def custom_action
    # Do something
  end
end

设置后,导航到 /first_models/2 会导致错误:

No route matches {:action=>"custom_action", :controller=>"SecondModelsController", :id=>"2"}

我不知道如何从原始请求中删除 id 参数以便路由匹配。

发生这种情况的原因是您调用 redirect_to 时使用了 Hash 参数。在内部 Rails 使用 url_for 构建最终位置,后者又使用 default_url_options ,后者使用当前资源的 ID。来自 API 文档:

Missing routes keys may be filled in from the current request's parameters (e.g. :controller, :action, :id and any other parameters that are placed in the path).

参见:http://api.rubyonrails.org/v5.1/classes/ActionDispatch/Routing/UrlFor.html

解决方案:使用命名路径助手。

运行 bundle exec rake routes 在命令行上获取所有路由和命名路径助手的列表。选择您需要的并按如下方式使用它:

redirect_to my_named_path_helper_path

不是参数问题:

class FirstModelsController < ApplicationController
  def show
    redirect_to controller: 'second_models', action: 'custom_action'
  end
end

您可以输入 rails 路线并查看您的所有路线以及 rails 如何识别它们。

这应该有效。但是你可以更明确地使用:

redirect_to custom_action_second_models_path