¿Cómo puedo saber la ruta actual en Rails?


Necesito saber la ruta actual en un filtro en Rieles. ¿Cómo puedo averiguar qué es?

Estoy haciendo recursos REST, y no veo rutas con nombre.

Author: the Tin Man, 2009-07-30

13 answers

Para averiguar 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"

Para averiguar la ruta, es decir, controlador, acción y parámetros:

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
 187
Author: Swanand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-25 14:08:37

Si usted está tratando de caso especial algo en una vista, se puede utilizar current_page? como en:

<% if current_page?(:controller => 'users', :action => 'index') %>

...o una acción y una identificación...

<% if current_page?(:controller => 'users', :action => 'show', :id => 1) %>

...o una ruta con nombre...

<% if current_page?(users_path) %>

...y

<% if current_page?(user_path(1)) %>

Debido a que current_page? requiere tanto un controlador como una acción, cuando me importa solo el controlador, hago un método current_controller? en ApplicationController:

  def current_controller?(names)
    names.include?(current_controller)
  end

Y úsalo así:

<% if current_controller?('users') %>

...que también funciona con múltiples nombres de controlador...

<% if current_controller?(['users', 'comments']) %>
 264
Author: IAmNaN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-16 00:58:15

La solución más sencilla que se me ocurre en 2015 (verificada con Rails 4, pero también debería funcionar con Rails 3)

request.url
# => "http://localhost:3000/lists/7/items"
request.path
# => "/lists/7/items"
 106
Author: weltschmerz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-15 00:38:19

Puedes hacer esto

Rails.application.routes.recognize_path "/your/path"

Funciona para mí en rails 3.1.0.rc4

 18
Author: Lucas Renan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-13 14:54:07

En rails 3 puede acceder al objeto Rack::Mount::RouteSet a través de Rails.aplicación.objeto de rutas, a continuación, llamar a reconocer en él directamente

route, match, params = Rails.application.routes.set.recognize(controller.request)

Que obtiene la primera (mejor) coincidencia, el siguiente bloque forma bucles sobre las rutas coincidentes:

Rails.application.routes.set.recognize(controller.request) do |r, m, p|
  ... do something here ...
end

Una vez que tenga la ruta, puede obtener el nombre de la ruta a través de route.name. Si necesita obtener el nombre de la ruta para una URL en particular, no la ruta de solicitud actual, entonces tendrá que simular un objeto de solicitud falso para pasar a rack, echa un vistazo a ActionController:: Routing:: Routes.recognize_path para ver cómo lo están haciendo.

 11
Author: KinOfCain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-21 23:05:48

Basado en la sugerencia de @ AmNaN (más detalles):

class ApplicationController < ActionController::Base

 def current_controller?(names)
  names.include?(params[:controller]) unless params[:controller].blank? || false
 end

 helper_method :current_controller?

end

Ahora puede llamarlo, por ejemplo, en un diseño de navegación para marcar los elementos de la lista como activos:

<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>

Para las rutas users y alerts, current_page? sería suficiente:

 current_page?(users_path)
 current_page?(alerts_path)

Pero con rutas anidadas y solicitud para todas las acciones de un controlador (comparable con items), current_controller? fue el mejor método para mí:

 resources :users do 
  resources :items
 end

La primera entrada del menú está activa para las siguientes rutas:

   /users/x/items        #index
   /users/x/items/x      #show
   /users/x/items/new    #new
   /users/x/items/x/edit #edit
 6
Author: neonmate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-24 18:05:44

Asumiré que te refieres al 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

Según su comentario a continuación, si necesita el nombre del controlador, simplemente puede hacer esto:

  private
    def pre_process
      self.controller_name        #  Will return "order"
      self.controller_class_name  # Will return "OrderController"
    end
 4
Author: Aaron Rustad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-30 14:27:13

Si también necesita los parámetros :

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"

Y recuerde que siempre puede llamar a <%= debug request.env %> en una vista para ver todas las opciones disponibles.

 4
Author: Darme,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-30 10:01:11

O, más elegantemente: request.path_info

Fuente:
Solicitar Documentación de Rack

 4
Author: dipole_moment,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-05 22:08:27

Petición.url

Solicitud.path # para obtener la ruta excepto la url base

 4
Author: Charles Skariah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-11 13:21:15

Puedes ver todas las rutas a través de rake:routes (esto podría ayudarte).

 2
Author: James Schorr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-30 02:55:53

Puede hacer request.env['REQUEST_URI'] para ver el URI completo solicitado.. producirá algo como below

http://localhost:3000/client/1/users/1?name=test
 0
Author: Vbp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-09 23:20:35

Puedes hacer esto:

def active_action?(controller)
   'active' if controller.remove('/') == controller_name
end

Ahora, puedes usar así:

<%= link_to users_path, class: "some-class #{active_action? users_path}" %>
 0
Author: Tiago Cassio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-02 18:14:12