【问题标题】:Rails route redirect using both constraints and a block?Rails路由重定向使用约束和块?
【发布时间】:2021-05-27 23:06:28
【问题描述】:

我正在为旧应用程序编写一个替换系统,我们希望旧 URL 重定向到新 URL 结构。我想使用 routes.rb 中的重定向助手来完成此操作。这对于简单的情况非常有用。但是,有些遗留标识符包含点。如果标识符包含一个点,我需要:

  1. 不丢失标识符的后半部分
  2. 用破折号替换点

所以,这是我在 rspec 中对此的测试:

    it "redirects requests correctly when there are dots in the eadid" do
      get "/collections/MC001.02.01/c00003"
      expect(response.code).to eq "301"
      expect(response).to redirect_to("http://www.example.com/catalog/MC001-02-01_c00003")
    end

我已经在几个地方阅读了重定向助手的文档。我看到我可以使用 constraints 正确获取整个 id,尽管有这些点。因此,这适用于获取整个 id:

get "/collections/:eadid/:componentid", to: redirect("/catalog/%{eadid}_%{componentid}"), constraints: { eadid: /([^\/])+?/ }

这将返回/catalog/MC001.02.01_c00003。关闭,但不太正确,因为我还需要用破折号替换点。

我还发现,如果我需要做一些更复杂的逻辑,例如字符串替换,我可以使用块格式,如下所示:

  get "/collections/:eadid/:componentid", to: redirect { |params, request|
    "/catalog/#{params[:eadid].gsub('.','-')}_#{params[:componentid]}"
  }

这不起作用,因为第一个点之后的eadid 的位已被删除,我可以查看是否同时检查paramsrequest

"action_dispatch.request.path_parameters"=>{:eadid=>"C0140", :componentid=>"c03411"}

我找不到配置为使用 both constraint 块的重定向助手的示例。对语法的猜测没有结果。有人知道这里的秘方吗?还是有更好的方法来解决我正在尝试做的事情?

谢谢!

咨询的来源:

【问题讨论】:

  • 请准确说明您的“对语法的猜测没有取得成果”。评论太长了,所以我同时写一个答案

标签: ruby-on-rails redirect routes


【解决方案1】:

您必须注意块和哈希之间相似(但不同)的语法

这是单行块的语法:

redirect {|params, request| ...}

这是哈希的语法:

{to: redirect("/catalog/%{eadid}_%{componentid}")}

当 Hash 是方法调用的最后一个参数时,{ 和关闭 } 是可选的,就像您的 get 一样。

现在,如果您想混合使用两者,您可能需要好好照顾自己的工作。

另一种解决方案是提取约束:

constraints(eadid: /[^\/]+/) do
  get "/collections/:eadid/:componentid", to: redirect { |params, request|
    "/catalog/#{params[:eadid].gsub('.','-')}_#{params[:componentid]}"
  }
end

【讨论】:

    【解决方案2】:

    我最终选择了这个,因为我发现它更容易阅读,但我可以确认 Geoffroy 的答案有效并且我已将其标记为已接受。

      get "/collections/:eadid/:componentid", constraints: { eadid: /([^\/])+?/ }, to: redirect { |params, _request|
        "/catalog/#{params[:eadid].tr('.', '-')}_#{params[:componentid]}"
      }
    

    Geoffroy 提出的列出我已经做出的语法猜测的建议也很有帮助。谢谢!

    【讨论】:

      猜你喜欢
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      相关资源
      最近更新 更多