我需要在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
其他回答
你可以通过rake:routes看到所有的路由(这可能对你有帮助)。
我找到了批准的答案,请求。env['PATH_INFO'],用于获取基本URL,但如果你有嵌套路由,它并不总是包含完整路径。你可以使用request。env['HTTP_REFERER']获取完整路径,然后查看它是否匹配给定的路由:
request.env['HTTP_REFERER'].match?(my_cool_path)
要查找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
如果你想在视图中对某些东西进行特殊处理,你可以使用current_page?如:
<% if current_page?(:controller => 'users', :action => 'index') %>
...或者一个动作和id。
<% if current_page?(:controller => 'users', :action => 'show', :id => 1) %>
...或者一条命名的路线……
<% if current_page?(users_path) %>
…
<% if current_page?(user_path(1)) %>
因为current_page ?需要控制器和动作,当我只关心控制器时,我做一个current_controller?方法:
def current_controller?(names)
names.include?(current_controller)
end
像这样使用它:
<% if current_controller?('users') %>
...这也适用于多个控制器名称…
<% if current_controller?(['users', 'comments']) %>
我假设你指的是URI:
class BankController < ActionController::Base
before_filter :pre_process
def index
# do something
end
private
def pre_process
logger.debug("The URL" + request.url)
end
end
根据你下面的评论,如果你需要控制器的名称,你可以简单地这样做:
private
def pre_process
self.controller_name # Will return "order"
self.controller_class_name # Will return "OrderController"
end