Ruby-on-rails 如何在 Rails 中找出当前路线?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1203892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I find out the current route in Rails?
提问by luca
I need to know the current route in a filter in Rails. How can I find out what it is?
我需要知道 Rails 过滤器中的当前路线。我怎样才能知道它是什么?
I'm doing REST resources, and see no named routes.
我正在做 REST 资源,但看不到命名路由。
采纳答案by Swanand
To find out URI:
要找出 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"
To find out the route i.e. controller, action and params:
要找出路线,即控制器、动作和参数:
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
回答by IAmNaN
If you are trying to special case something in a view, you can use current_page?as in:
如果您尝试在视图中对某些内容进行特殊处理,则可以使用以下current_page?方式:
<% if current_page?(:controller => 'users', :action => 'index') %>
...or an action and id...
...或一个动作和ID ...
<% if current_page?(:controller => 'users', :action => 'show', :id => 1) %>
...or a named route...
...或命名路线...
<% if current_page?(users_path) %>
...and
...和
<% if current_page?(user_path(1)) %>
Because current_page?requires both a controller and action, when I care about just the controller I make a current_controller?method in ApplicationController:
因为current_page?需要控制器和动作,当我只关心控制器时,我current_controller?在 ApplicationController 中创建了一个方法:
def current_controller?(names)
names.include?(current_controller)
end
And use it like this:
并像这样使用它:
<% if current_controller?('users') %>
...which also works with multiple controller names...
...也适用于多个控制器名称...
<% if current_controller?(['users', 'comments']) %>
回答by dchacke
Simplest solution I can come up with in 2015 (verified using Rails 4, but should also work using Rails 3)
我可以在 2015 年提出的最简单的解决方案(使用 Rails 4 验证,但也应该使用 Rails 3)
request.url
# => "http://localhost:3000/lists/7/items"
request.path
# => "/lists/7/items"
回答by Lucas Renan
You can do this
你可以这样做
Rails.application.routes.recognize_path "/your/path"
It works for me in rails 3.1.0.rc4
它适用于 Rails 3.1.0.rc4
回答by KinOfCain
In rails 3 you can access the Rack::Mount::RouteSet object via the Rails.application.routes object, then call recognize on it directly
在 rails 3 中,您可以通过 Rails.application.routes 对象访问 Rack::Mount::RouteSet 对象,然后直接在其上调用识别
route, match, params = Rails.application.routes.set.recognize(controller.request)
that gets the first (best) match, the following block form loops over the matching routes:
获得第一个(最佳)匹配,以下块形式循环匹配路由:
Rails.application.routes.set.recognize(controller.request) do |r, m, p|
... do something here ...
end
once you have the route, you can get the route name via route.name. If you need to get the route name for a particular URL, not the current request path, then you'll need to mock up a fake request object to pass down to rack, check out ActionController::Routing::Routes.recognize_path to see how they're doing it.
获得路线后,您可以通过 route.name 获取路线名称。如果您需要获取特定 URL 的路由名称,而不是当前请求路径,那么您需要模拟一个假请求对象以向下传递到机架,请查看 ActionController::Routing::Routes.recognize_path 以查看他们是怎么做的。
回答by neonmate
Based on @AmNaN suggestion (more details):
基于@AmNaN 建议(更多细节):
class ApplicationController < ActionController::Base
def current_controller?(names)
names.include?(params[:controller]) unless params[:controller].blank? || false
end
helper_method :current_controller?
end
Now you can call it e.g. in a navigation layout for marking list items as active:
现在您可以在导航布局中调用它,以将列表项标记为活动:
<ul class="nav nav-tabs">
<li role="presentation" class="<%= current_controller?('items') ? 'active' : '' %>">
<%= link_to user_items_path(current_user) do %>
<i class="fa fa-cloud-upload"></i>
<% end %>
</li>
<li role="presentation" class="<%= current_controller?('users') ? 'active' : '' %>">
<%= link_to users_path do %>
<i class="fa fa-newspaper-o"></i>
<% end %>
</li>
<li role="presentation" class="<%= current_controller?('alerts') ? 'active' : '' %>">
<%= link_to alerts_path do %>
<i class="fa fa-bell-o"></i>
<% end %>
</li>
</ul>
For the usersand alertsroutes, current_page?would be enough:
对于users和alerts路线,current_page?就足够了:
current_page?(users_path)
current_page?(alerts_path)
But with nested routes and request for all actions of a controller (comparable with items), current_controller?was the better method for me:
但是对于控制器的所有操作的嵌套路由和请求(与 相比items),current_controller?对我来说是更好的方法:
resources :users do
resources :items
end
The first menu entry is that way active for the following routes:
第一个菜单条目对以下路线有效:
/users/x/items #index
/users/x/items/x #show
/users/x/items/new #new
/users/x/items/x/edit #edit
回答by dipole_moment
Or, more elegantly: request.path_info
或者,更优雅地: request.path_info
Source:
Request Rack Documentation
来源:
请求机架文档
回答by Darme
Should you also need the parameters:
您是否还需要参数:
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"
And remember you can always call <%= debug request.env %>in a view to see all the available options.
请记住,您始终可以<%= debug request.env %>在视图中调用以查看所有可用选项。
回答by Aaron Rustad
I'll assume you mean the URI:
我假设您指的是 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
As per your comment below, if you need the name of the controller, you can simply do this:
根据您在下面的评论,如果您需要控制器的名称,您可以简单地执行以下操作:
private
def pre_process
self.controller_name # Will return "order"
self.controller_class_name # Will return "OrderController"
end
回答by Charles Skariah
request.url
请求.url
request.path #to get path except the base url
request.path #获取除基本url之外的路径

