[英]Get current path with name of query params in the path
在 Rails controller 中,如何访问当前路径,但查询参数的格式与rails routes
中的格式相同?
因此,例如,在www.test.com/record/3中,我正在寻找的助手将返回record/:id
。
我试过request.path
但它没有返回 URL 中参数的名称。它返回实际路径,这不是我想要的。
您要查找的内容称为动态段(或有时称为占位符)。
您可以使用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"}
与参数 object 不同,它不包含来自查询字符串或请求正文的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.