[英]How to determine which controller has been called from ApplicationController?
I would like to put one method inside my ApplicationController
and launch it only in case when some controllers are called. 我想在
ApplicationController
放入一个方法,并仅在调用某些控制器的情况下启动它。 Similarly to devise parameters sanitizer: 与设计参数消毒器类似:
before_action :configure_permitted_parameters, if: :devise_controller?
I've tried: 我试过了:
before_action :recent_discussions, if: :first_controller? || :second_controller? || :third_controller?
However first_controller?
但是
first_controller?
etc are undefined methods. 等是未定义的方法。
Is there a way to call something in ApplicationController
only under specific controllers? 有没有一种方法只能在特定控制器下在
ApplicationController
调用某些东西?
Presuming you meant ||
假设您的意思是
||
instead of &&
in your question's pseudo code ( &&
makes no sense), this would work: 而不是
&&
在你的问题的伪代码( &&
是没有意义的),这会工作:
FANCY_CONTROLLERS = %w[FirstController SecondController ThirdController]
before_action :recent_discussions,
if: proc { FANCY_CONTROLLERS.include? "#{controller_name.camelize}Controller" }
Put this in your application 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
And put this in your special controllers 并将其放在您的特殊控制器中
class FirstController < ApplicationController
before_action :recent_discussions, if: :special_controller?
# more code
end
You can use request.referrer
to get the path of the previous action. 您可以使用
request.referrer
获取上一个操作的路径。
To get the controller responsible for that action, use: Rails.application.routes.recognize_path(request.referrer)[:controller]
要使控制器负责该操作,请使用:
Rails.application.routes.recognize_path(request.referrer)[:controller]
You could define private method def my_controller?; end
您可以定义私有方法
def my_controller?; end
def my_controller?; end
in ApplicationController
, and use filter before_action :recent_discussions, if: :my_controller?
在
ApplicationController
def my_controller?; end
,并使用过滤器before_action :recent_discussions, if: :my_controller?
Then, in controllers you want this code actually run, redefine def my_controller?; true; end
然后,在要实际运行此代码的控制器中,重新定义
def my_controller?; true; end
def my_controller?; true; end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.