【问题标题】:Rails- redirect_to carrying over unwanted idRails-redirect_to 携带不需要的 id
【发布时间】:2018-03-10 17:30:20
【问题描述】:

我正在尝试从显示操作重定向到自定义收集操作,但 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 参数,以便路由匹配。

【问题讨论】:

    标签: ruby-on-rails activerecord url-routing


    【解决方案1】:

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

    可以从当前请求的参数(例如 :controller、:action、:id 和放置在路径中的任何其他参数)填充缺少的路由键。

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

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

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

    redirect_to my_named_path_helper_path

    【讨论】:

      【解决方案2】:

      问题不是参数:

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

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

      这应该可行。但是,您可以更明确地使用:

      redirect_to custom_action_second_models_path
      

      【讨论】:

        猜你喜欢
        • 2015-07-09
        • 2017-10-21
        • 1970-01-01
        • 1970-01-01
        • 2016-04-13
        • 1970-01-01
        • 2010-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多