Jak mogę sprawdzić bieżącą trasę w Rails?

Muszę znać bieżącą trasę w filtrze w Rails. Jak mogę się dowiedzieć, co to jest?

Robię REST resources, i nie widzę nazwanych tras.

Author: the Tin Man, 2009-07-30

13 answers

Aby dowiedzieć się 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"

Aby poznać trasę tj. kontroler, działanie i 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
 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/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-25 14:08:37

Jeśli próbujesz coś specjalnego w widoku, możesz użyć current_page? jak w:

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

...lub akcji i id...

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

...albo wyznaczoną trasę...

<% if current_page?(users_path) %>

...oraz

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

Ponieważ current_page? wymaga zarówno kontrolera jak i akcji, kiedy zależy mi tylko na kontrolerze wykonuję metodę current_controller? w ApplicationController:

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

I używaj go tak:

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

...który działa również z wieloma nazwami kontrolerów...

<% 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-16 00:58:15

Najprostsze rozwiązanie, jakie mogę wymyślić w 2015 roku (zweryfikowane przy użyciu Rails 4, ale powinno działać również przy użyciu 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-15 00:38:19

Możesz to zrobić

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

U mnie działa w 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/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-13 14:54:07

W rails 3 możesz uzyskać dostęp do obiektu Rack::Mount:: RouteSet za pomocą Rails.podanie.routes object, a następnie wywołanie recognize on it directly

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

, który otrzymuje pierwsze (najlepsze) dopasowanie, następujące bloki tworzą pętle nad pasującymi trasami:

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

Gdy już masz trasę, możesz uzyskać nazwę trasy poprzez route.name. jeśli chcesz uzyskać nazwę trasy dla konkretnego adresu URL, a nie bieżącą ścieżkę żądania, musisz sfałszować fałszywy obiekt żądania, aby przekazać go do Szafy rack, sprawdź ActionController:: Routing:: Routes.recognize_path, aby zobaczyć, jak to robią.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-21 23:05:48

Na podstawie sugestii @ AmNaN (więcej szczegółów):

class ApplicationController < ActionController::Base

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

 helper_method :current_controller?

end

Teraz można go nazwać np. w układzie nawigacyjnym do oznaczania elementów listy jako aktywne:

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

Dla users i alerts, current_page? wystarczyłoby:

 current_page?(users_path)
 current_page?(alerts_path)

Ale z zagnieżdżonymi trasami i żądaniem wszystkich akcji kontrolera (porównywalne z items), current_controller? była dla mnie lepsza metoda:

 resources :users do 
  resources :items
 end

Pierwsza pozycja menu jest w ten sposób aktywna dla następujących tras:

   /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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-24 18:05:44

Zakładam, że masz na myśli 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

Zgodnie z Twoim komentarzem poniżej, jeśli potrzebujesz nazwy kontrolera, możesz po prostu to zrobić:

  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/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-30 14:27:13

Jeśli potrzebujesz również parametry :

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"

I pamiętaj, że zawsze możesz wywołać <%= debug request.env %> w widoku, aby zobaczyć wszystkie dostępne opcje.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-30 10:01:11

Lub bardziej elegancko: request.path_info

Źródło:
Poproś O Dokumentację Regału

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-05 22:08:27

Prośba.url

Prośba.ścieżka #do pobrania ścieżki z wyjątkiem podstawowego adresu url

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-11 13:21:15

Możesz zobaczyć wszystkie trasy poprzez rake: routes (to może Ci pomóc).

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-30 02:55:53

Możesz zrobić request.env['REQUEST_URI'], aby zobaczyć pełny żądany URI.. wyświetli coś takiego jak poniżej

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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-09 23:20:35

Możesz to zrobić:

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

Teraz możesz użyć TAK:

<%= 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-02 18:14:12