programing

레일즈의 현재 경로는 어떻게 알 수 있습니까?

starjava 2023. 6. 6. 00:23
반응형

레일즈의 현재 경로는 어떻게 알 수 있습니까?

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

REST 리소스를 수행하고 있는데 지정된 경로가 없습니다.

보기에서 특정 항목을 특수하게 사용하려는 경우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?Application Controller의 메서드:

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

다음과 같이 사용합니다.

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

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

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

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

2015년에 생각해 낼 수 있는 가장 간단한 솔루션(레일 4를 사용하여 검증되지만 레일 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 개체를 통해 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::라우팅: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>

를 위해users그리고.alerts경로,current_page?충분할 것 같습니다.

 current_page?(users_path)
 current_page?(alerts_path)

그러나 중첩된 경로 및 컨트롤러의 모든 작업에 대한 요청(비교 가능)items),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.path_info

출처:
랙 문서 요청

매개 변수도 필요한 경우:

current_fullpath = request.env['ORIGINAL_FULLPATH']http://example.com/my/test/path?param_n=N 을 검색하는 경우그러면 current_full 경로가 "/my/test/path?param_n="을 가리킵니다.N"

그리고 당신이 항상 전화할 수 있다는 것을 기억하세요.<%= debug request.env %>사용 가능한 모든 옵션을 확인할 수 있습니다.

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

아래 설명에 따라 컨트롤러 이름이 필요한 경우 다음과 같이 간단히 수행할 수 있습니다.

  private
    def pre_process
      self.controller_name        #  Will return "order"
      self.controller_class_name  # Will return "OrderController"
    end

request.url

request.path #: 기본 URL을 제외한 경로를 가져옵니다.

레이크:루트를 통해 모든 경로를 볼 수 있습니다(도움이 될 수 있습니다).

다음을 수행할 수 있습니다.

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

이제 다음과 같이 사용할 수 있습니다.

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

저는 승인된 답변을 찾았습니다.request.env['PATH_INFO']기본 URL을 가져오는 데 사용되지만 중첩된 경로가 있는 경우에는 항상 전체 경로가 포함되지 않습니다.사용할 수 있습니다.request.env['HTTP_REFERER']전체 경로를 가져온 다음 지정된 경로와 일치하는지 확인합니다.

request.env['HTTP_REFERER'].match?(my_cool_path)

할수있습니다request.env['REQUEST_URI']요청된 전체 URI를 확인합니다.그것은 아래와 같은 것을 출력할 것입니다.

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

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

반응형