Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to Rails: How are you using application_controller.rb in your rails app?

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?

like image 757
user836087 Avatar asked Oct 21 '12 06:10

user836087


1 Answers

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.

like image 149
Erez Rabih Avatar answered Oct 14 '22 00:10

Erez Rabih