I am just getting into rails and begining to understand it slowly. Can someone explain or give me ideas on the benefits or when and whys for coding inside the application_controller? What are some usecases. How are you using the application controller for your rails app? I dont want to put too much code in there because from what I understand, this controller gets called for every request. Is this true?
Share
ApplicationController is practically the class which every other controller in you application is going to inherit from (although this is not mandatory in any mean).
I agree with the attitude of not messing it with too much code and keeping it clean and tidy, although there are some cases in which ApplicationController would be a good place to put your code at.
For example: If you are working with multiple locale files and want to set the locale based on the URL requested you’d do this in your ApplicationController:
This will spare you the headache of setting locale in each controller separately. You do it once, and you have the locale set all over the system.
Same goes for the famous
protect_from_forgerywhich can be found on the default ApplicationController of a new rails app.Another use case could be rescuing all exception of a certain type in your application:
In general, if you have a feature that all other controllers would definitely use, ApplicationController might be a good place for it.