Programming

Rails에서 현재 경로를 어떻게 알 수 있습니까?

procodes 2020. 5. 6. 22:22
반응형

Rails에서 현재 경로를 어떻게 알 수 있습니까?


Rails의 필터에서 현재 경로를 알아야합니다. 그것이 무엇인지 어떻게 알 수 있습니까?

REST 리소스를 사용하고 있으며 이름이 지정된 경로가 없습니다.


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

뷰에서 무언가를 특수하게 처리하려는 경우 다음과 current_page?같이 사용할 수 있습니다 .

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

... 또는 행동과 아이디 ...

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

... 또는 명명 된 노선 ...

<% if current_page?(users_path) %>

...과

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

current_page?컨트롤러와 액션이 모두 필요 하기 때문에 컨트롤러 만 신경 쓰면 current_controller?ApplicationController 에서 메소드를 만듭니다 .

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

그리고 이것을 다음과 같이 사용하십시오 :

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

... 여러 컨트롤러 이름으로도 작동합니다 ...

<% if current_controller?(['users', 'comments']) %>

2015 년에 생각해 볼 수있는 가장 간단한 솔루션 (Rails 4를 사용하여 확인되었지만 Rails 3을 사용하여 작동해야 함)

request.url
# => "http://localhost:3000/lists/7/items"
request.path
# => "/lists/7/items"

당신은 이것을 할 수 있습니다

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

레일 3.1.0.rc4에서 작동합니다.


레일 3에서는 Rails.application.routes 객체를 통해 Rack :: Mount :: RouteSet 객체에 액세스 한 다음 바로 인식을 호출 할 수 있습니다.

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.recognize_path를 확인하십시오. 그들이 어떻게하고 있는지


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

들어 usersalerts경로 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:

 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

Or, more elegantly: request.path_info

Source:
Request Rack Documentation


I'll assume you mean the 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

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.


request.url

request.path #to get path except the base url


You can see all routes via rake:routes (this might help you).


You can do request.env['REQUEST_URI'] to see the full requested URI.. it will output something like below

http://localhost:3000/client/1/users/1?name=test

You can do this:

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

Now, you can use like this:

<%= link_to users_path, class: "some-class #{active_action? users_path}" %>

참고URL : https://stackoverflow.com/questions/1203892/how-can-i-find-out-the-current-route-in-rails

반응형