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?
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:
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
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_forgery
which 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:
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
private
def record_not_found
render :text => "404 Not Found", :status => 404
end
In general, if you have a feature that all other controllers would definitely use, ApplicationController might be a good place for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With