小编典典

如何在 Rails 中找到当前路线?

all

我需要知道 Rails 过滤器中的当前路线。我怎样才能知道它是什么?

我正在做 REST 资源,但没有看到命名路由。


阅读 131

收藏
2022-06-01

共1个答案

小编典典

要找出 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
2022-06-01