Reputation: 185
I don't know exactly why application_controller needs in ruby on rails
my idea is...
def route_not_found
render file: Rails.public_path.join('404.html'), status: 404, layout: false
end
def not_login?
if current_user.nil?
redirect_to login_path, notice: 'You have to log in'
end
end
like this, and I can used this method in other controller as before_action's argument. so I thought application_controller is for defining method which used for before_action.
is my thinking correct? I want to know what application controller's true usage
Upvotes: 0
Views: 238
Reputation: 46
Application controller helps abstract out shared logic of the controllers in your project. You can use it for various application wide tasks such as error handling, common methods, setting before actions, setting helper methods, etc.
As mentioned, methods that are used by multiple controllers can be placed here (ex. def current_user
). However, if a method is only shared by a few controllers within a domain, it is better to place it into a different parent controller in that same domain to keep things organized.
In this example, the controllers would inherit from the custom parent controller and the custom parent controller would inherit from application controller.
You can set before actions in application controller and call them from application controller as well, just define the method and call before_action :method_name at the top of the application controller. That before action will run before all controller actions. If you only want it to run on certain controllers, then call it the way you described, just from the controller where you want it.
Upvotes: 2