我需要在Rails中的过滤器中知道当前路由。我怎么才能知道是什么?
我正在使用REST资源,没有看到命名路由。
我需要在Rails中的过滤器中知道当前路由。我怎么才能知道是什么?
我正在使用REST资源,没有看到命名路由。
当前回答
在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。来看看它们是怎么做的。
其他回答
你可以这样做
Rails.application.routes.recognize_path "/your/path"
它在rails 3.1.0.rc4中为我工作
根据@AmNaN的建议(更多细节):
class ApplicationController < ActionController::Base
def current_controller?(names)
names.include?(params[:controller]) unless params[:controller].blank? || false
end
helper_method :current_controller?
end
现在你可以调用它,例如在导航布局中标记列表项为活动:
<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>
对于users和alerts路由,current_page?这就足够了:
current_page?(users_path)
current_page?(alerts_path)
但是使用嵌套路由和请求控制器的所有动作(与项目相比),current_controller?对我来说是更好的方法
resources :users do
resources :items
end
第一个菜单项是为以下路由激活的方式:
/users/x/items #index
/users/x/items/x #show
/users/x/items/new #new
/users/x/items/x/edit #edit
request.url
请求。获取除基本url之外的路径
你可以请求。env['REQUEST_URI']查看完整的请求URI..它将输出如下内容
http://localhost:3000/client/1/users/1?name=test
如果你想在视图中对某些东西进行特殊处理,你可以使用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']) %>