【问题标题】:Get current path with name of query params in the path获取路径中查询参数名称的当前路径
【发布时间】:2023-01-11 08:43:27
【问题描述】:

在 Rails 控制器中,如何访问当前路径,但查询参数的格式与 rails routes 中的格式相同?

因此,例如,在 www.test.com/record/3 中,我正在寻找的助手将返回 record/:id。

我试过 request.path 但它没有返回 URL 中参数的名称。它返回实际路径,这不是我想要的。

【问题讨论】:

  • 假设您知道参数名称,并且它过去不是动态的。您可以确保将参数名称放在 const 上。如果您希望收到record/:id,您可以肯定拥有密钥id。也许 params.keys.slice(2..).map(&:to_sym) 可以帮助您获取参数名称。
  • 你是如何在你的config/routes.rb中定义路线的?因为在您的示例中,我希望像 record/3 这样的路由返回 :controller/:id。
  • 你为什么需要它?

标签: ruby-on-rails ruby


【解决方案1】:

您要查找的内容称为 dynamic segments(或有时称为占位符)。

您可以使用request.path_parameters.except(:action, :controller) 以编程方式为给定请求获取它们。

# route is defined as 'get /:foo/:bar'
irb(main):013:0> app.get '/a/b?x=2'
Started GET "/a/b?x=2" for 127.0.0.1 at 2023-01-11 01:08:53 +0100
Processing by PagesController#home as HTML
  Parameters: {"x"=>"2", "foo"=>"a", "bar"=>"b"}
  Rendering layout layouts/application.html.erb
  Rendering pages/home.html.erb within layouts/application
  Rendered pages/home.html.erb within layouts/application (Duration: 0.1ms | Allocations: 7)
  Rendered layout layouts/application.html.erb (Duration: 2.7ms | Allocations: 2363)
Completed 200 OK in 4ms (Views: 3.3ms | Allocations: 2675)


=> 200
irb(main):014:0> app.request.path_parameters
=> {:controller=>"pages", :action=>"home", :foo=>"a", :bar=>"b"} 

与 params 对象不同,它不包含来自查询字符串或请求正文的参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多