![](/img/trans.png)
[英]Determine the requested Controller in - 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.