[英]Determine if path exists as route in Rails controller
I want to know if an arbitrary path can be mapped to a route我想知道是否可以将任意路径映射到路由
recognized_request_for accomplishes what I want, but I can't get it to work in my controller. identify_request_for 完成了我想要的,但我无法让它在我的控制器中工作。
Specifically, how can I execute recognized_request_for or something that accomplishes the same task from my controller?具体来说,我怎样才能从我的控制器执行recognized_request_for或完成相同任务的东西?
For Rails 3 the call is对于 Rails 3,调用是
Rails.application.routes.recognize_path
Instead of代替
ActionController::Routing::Routes.recognize_path
Example:例子:
def path_exists?(path)
Rails.application.routes.recognize_path(path)
true
rescue ActionController::RoutingError
false
end
SOLUTION:解决方案:
@related_page_path = '/' + @page.path
begin
ActionController::Routing::Routes.recognize_path(@related_page_path, :method => :get)
rescue
@related_page_path = nil
end
If you want to connect an arbitrary path the a controller and and action, you can use map.connect
如果要连接控制器和动作的任意路径,可以使用
map.connect
map.connect '/any/random/string/of/stuff', :controller => 'items', :action => 'new'
You can even call out embedded param designations in the path:您甚至可以在路径中调用嵌入的参数名称:
map.connect '/seeking/room/for/[:number_of_nights]/nights', :controller => 'rooms', :action => 'index'
with the above you will receive the value represented in the url as part of the params
hash in the controller.使用上述内容,您将收到 url 中表示的值,作为控制器中
params
散列的一部分。
您可能会动态生成路由助手方法并查看它是否存在(使用 respond_to? 甚至只是捕获任何抛出的异常)。
I recently came across an issue where I had to check if a path existed given an array of possible paths.我最近遇到了一个问题,在给定一组可能的路径的情况下,我必须检查路径是否存在。 I had tried the above suggestion
Rails.application.routes.recognize_path
, but it's depericated as of rails 4.2.1
.我已经尝试了上述建议
Rails.application.routes.recognize_path
,但它从rails 4.2.1
就已经废弃了。 I used the following instead:我改用以下内容:
Rails.application.routes.named_routes.routes.any?{ |key, value| key.to_s === "new_article" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.