I would like to put one method inside my ApplicationController
and launch it only in case when some controllers are called. 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?
etc are undefined methods.
Is there a way to call something in ApplicationController
only under specific controllers?
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.
To get the controller responsible for that action, use: Rails.application.routes.recognize_path(request.referrer)[:controller]
You could define private method def my_controller?; end
def my_controller?; end
in ApplicationController
, and use filter 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.