我需要在Rails中的过滤器中知道当前路由。我怎么才能知道是什么?
我正在使用REST资源,没有看到命名路由。
我需要在Rails中的过滤器中知道当前路由。我怎么才能知道是什么?
我正在使用REST资源,没有看到命名路由。
当前回答
你可以这样做:
def active_action?(controller)
'active' if controller.remove('/') == controller_name
end
现在,你可以这样用:
<%= link_to users_path, class: "some-class #{active_action? users_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
你可以通过rake:routes看到所有的路由(这可能对你有帮助)。
我能在2015年提出的最简单的解决方案(使用Rails 4验证,但也应该使用Rails 3)
request.url
# => "http://localhost:3000/lists/7/items"
request.path
# => "/lists/7/items"
你可以这样做
Rails.application.routes.recognize_path "/your/path"
它在rails 3.1.0.rc4中为我工作
或者更优雅地说:request.path_info
来源: 请求机架文档