反向 rails 路由:从 URL 中查找操作名称 [英] Reverse rails routing: find the action name from the URL
问题描述
我了解如何将 :controller
、:action、
:etc
转换为 URL.我正在寻找相反的方法,如何从 URL 中找到 rails 路由器将调用的操作?
I understand how to turn :controller
, :action,
:etc
into a URL. I'm looking to do the reverse, how can the action that the rails router will call be found from the URL?
推荐答案
其他人可能有更短的方法来执行此操作,但如果您只是评估 URL,则转到 ActionController::Routing::RouteSet
类
someone else might have a shorter way to do this, but if you are just evaluating a URL, then you go to the ActionController::Routing::RouteSet
class
对于 config.routes.rb
map.resources :sessions
要查找的代码是:
ActionController::Routing::Routes.recognize_path('/sessions/new', {:method => :get})
#=> {:controller => 'sessions', :action => 'new'}
对:
ActionController::Routing::Routes.recognize_path('/sessions/1/edit', {:method => :get})
#=> {:controller => 'sessions', :action => 'edit', :id => 1}
错误 - 如果没有显式添加 method
,它将默认匹配 /:controller/:action/:id
:
Wrong - without the method
being explicitly added, it will default match to /:controller/:action/:id
:
ActionController::Routing::Routes.recognize_path('/sessions/1/edit')
#=> {:controller => 'sessions', :action => '1', :id => 'edit'}
如果您在操作中并想知道,调用 params[:action]
If you are within the action and would like to know, it is quite a bit easier by calling params[:action]
你想知道的关于路由集的一切都可以在这里找到:http://caboo.se/doc//classes/ActionController/Routing/RouteSet.html#M004878
everything you ever wanted to know about routeset can be found here: http://caboo.se/doc//classes/ActionController/Routing/RouteSet.html#M004878
希望这有帮助!
这篇关于反向 rails 路由:从 URL 中查找操作名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!