2010-04-26 80 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