2010-04-26 75 views

回答

5

有以下方法:

>> ActionController::Routing::Routes.recognize_path("/posts/") 
=> {:action=>"index", :controller=>"posts"} 

如果你仅仅使用你的路线字符串(如"posts_path"),然后我在上下文猜你使用这个,你应该能够做

ActionController::Routing::Routes.recognize_path(send("posts_path".to_sym)) 

顺便说一句这太教育对我来说:)

+0

啊,你已经做了大部分工作自己:) – 2010-04-26 16:21:48

+1

THX的: )那么'send(:post_path)'是什么? – fl00r 2010-04-26 16:27:33

+0

这就是你如何在ruby中调用具有任意名称的方法:)在这种情况下,如果你有一个像''posts_path''这样的字符串,并且你想获取'posts_path'方法的值,那么你只需要'send (“posts_path”)'(你甚至不需要转换为符号)。这是红宝石的核心概念,你最好熟悉:) – 2010-04-26 16:34:07

12

在Rails 3,您可以执行以下操作:

Rails.application.routes.recognize_path "/accounts/1" 
# {:action=>"show", :controller=>"accounts", :id=>"1"} 

使用ActionController::Routing::Routes.recognize_path保持扔

的ActionController :: RoutingError例外:无路由匹配“/客户/ 1

+0

注意这也适用于完整网址:'Rails.application.routes.recognize_path'http:// example.com/accounts/1'' – tee 2014-05-15 19:08:20