簡體   English   中英

如何確定已從ApplicationController調用了哪個控制器?

[英]How to determine which controller has been called from ApplicationController?

我想在ApplicationController放入一個方法,並僅在調用某些控制器的情況下啟動它。 與設計參數消毒器類似:

before_action :configure_permitted_parameters, if: :devise_controller?

我試過了:

before_action :recent_discussions, if: :first_controller? || :second_controller? || :third_controller?

但是first_controller? 等是未定義的方法。

有沒有一種方法只能在特定控制器下在ApplicationController調用某些東西?

假設您的意思是|| 而不是&&在你的問題的偽代碼( &&是沒有意義的),這會工作:

FANCY_CONTROLLERS = %w[FirstController SecondController ThirdController]
before_action :recent_discussions,
  if: proc { FANCY_CONTROLLERS.include? "#{controller_name.camelize}Controller" }

把它放在你的應用程序控制器中

class ApplicationController < ActionController::Base
  # more code

  def special_controller?
    controller = params[:controller]
    special_controllers = %w(first second third)
    special_controllers.include? controller
  end
end

並將其放在您的特殊控制器中

class FirstController < ApplicationController
  before_action :recent_discussions, if: :special_controller?

  # more code
end

您可以使用request.referrer獲取上一個操作的路徑。

要使控制器負責該操作,請使用: Rails.application.routes.recognize_path(request.referrer)[:controller]

您可以定義私有方法def my_controller?; end ApplicationController def my_controller?; end ,並使用過濾器before_action :recent_discussions, if: :my_controller?

然后,在要實際運行此代碼的控制器中,重新定義def my_controller?; true; end def my_controller?; true; end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM