我需要在Rails中的过滤器中知道当前路由。我怎么才能知道是什么?
我正在使用REST资源,没有看到命名路由。
我需要在Rails中的过滤器中知道当前路由。我怎么才能知道是什么?
我正在使用REST资源,没有看到命名路由。
当前回答
要查找URI:
current_uri = request.env['PATH_INFO']
# If you are browsing http://example.com/my/test/path,
# then above line will yield current_uri as "/my/test/path"
找到路径,即控制器,动作和参数:
path = ActionController::Routing::Routes.recognize_path "/your/path/here/"
# ...or newer Rails versions:
#
path = Rails.application.routes.recognize_path('/your/path/here')
controller = path[:controller]
action = path[:action]
# You will most certainly know that params are available in 'params' hash
其他回答
你可以这样做
Rails.application.routes.recognize_path "/your/path"
它在rails 3.1.0.rc4中为我工作
你可以这样做:
def active_action?(controller)
'active' if controller.remove('/') == controller_name
end
现在,你可以这样用:
<%= link_to users_path, class: "some-class #{active_action? users_path}" %>
如果你还需要这些参数:
current_fullpath = request.env['ORIGINAL_FULLPATH'] # If you are browsing http://example.com/my/test/path?param_n=N # then current_fullpath will point to "/my/test/path?param_n=N"
记住,你总是可以调用<%=调试请求。Env %>,以查看所有可用选项。
在rails 3中,你可以通过rails .application.routes对象访问Rack::Mount::RouteSet对象,然后直接调用它上的recognition函数
route, match, params = Rails.application.routes.set.recognize(controller.request)
得到第一个(最佳)匹配,下面的块形式循环匹配的路由:
Rails.application.routes.set.recognize(controller.request) do |r, m, p|
... do something here ...
end
一旦有了路由,就可以通过route.name获取路由名。如果您需要获取特定URL的路由名称,而不是当前请求路径,那么您需要模拟一个假请求对象以传递到机架,请检查ActionController::Routing::Routes。来看看它们是怎么做的。
request.url
请求。获取除基本url之外的路径