Search code examples
ruby-on-railsbefore-filter

When should I user before_filter vs helper_method?


I have the following application_controller method:

  def current_account
    @current_account ||= Account.find_by_subdomain(request.subdomain)
  end

Should I be calling it using a before_filter or a helper_method? What's the difference between the two and what should I consider in terms of the trade-offs in this case?

Thanks.

UPDATE FOR BETTER CLARITY

I'm finding that I can user the before_filter instead of the helper_method in that I'm able to call controller defined methods from my views. Perhaps it's something in how I arranged my code, so here is what I have:

controllers/application_controller.rb

class ApplicationController < ActionController::Base

  protect_from_forgery

  include SessionsHelper

  before_filter :current_account
  helper_method :current_user

end

helpers/sessions_helper.rb

module SessionsHelper

  private

  def current_account
    @current_account ||= Account.find_by_subdomain(request.subdomain)
  end

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def logged_in?
    if current_user
      return true
    else
      return false
    end
  end
end

controllers/spaces_controller.rb

class SpacesController < ApplicationController

  def home
    unless logged_in?
      redirect_to login_path
    end
  end
end

views/spaces/home.html.erb

<%= current_account.inspect %>

In theory, this shouldn't work, right?


Solution

  • There is no relationship between using before_filter or helper_method. You should use helper method when you have a method in your controller that you would like to reuse in your views, this current_account might be a nice example for helper_method if you need to use it in your views.