user836087
user836087

Reputation: 2491

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?

Upvotes: 5

Views: 2921

Answers (2)

Dreyfuzz
Dreyfuzz

Reputation: 476

I use it for helpers and methods that need to be used in multiple controllers. A good example is Ryan Bates "Super Simple Authentication from Scratch"

class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :admin?

  protected

  def authorize
    unless admin?
      flash[:error] = 'Sorry, that page is only for admins'
      redirect_to :root
      false
    end
  end

  def admin?
    session[:password] == "password"
  end
end

Then you can all a before_filter :authorize or if admin? from anywhere in your app.

Upvotes: 0

Erez Rabih
Erez Rabih

Reputation: 15788

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.

Upvotes: 8

Related Questions