Question

I want to set something up so that if an Account within my app is disabled, I want all requests to be redirected to a "disabled" message.

I've set this up in my ApplicationController:

class ApplicationController < ActionController::Base
  before_filter :check_account

  def check_account
    redirect_to :controller => "main", :action => "disabled" and return if !$account.active?
  end
end

Of course, this doesn't quite work as it goes into an infinite loop if the Account is not active. I was hoping to use something like:

redirect_to :controller => "main", :action => "disabled" and return if !$account.active? && @controller.controller_name != "main" && @controller.action_name != "disabled"

but I noticed that in Rails v2.1 (what I'm using), @controller is now controller and this doesn't seem to work in ApplicationController.

What would be the best way to implement something like this?

Was it helpful?

Solution

You could also use a skip_before_filter for the one controller/method you don't want to have the filter apply to.

OTHER TIPS

You have several options.

If your action method "disabled" is uniquely named in the scope of the application, you can add an exception to the before_filter call, like this:

before_filter :check_account, :except => :disabled

If you want to check specifically for the controller and action in the filter, you should note that this code is already part of the controller object. You can refer to it as "self," like so:

  def check_account
    return if self.controller_name == "main" && self.action_name == "disabled"

    redirect_to :controller => "main", :action => "disabled" and return if !$account.active?
  end

Finally, if you like, you can overwrite the filter method from within MainController.rb:

  def check_account
    return if action_name == "disabled"
    super
  end

How about first getting rid of that global variable $account. You are basically setting yourself up for some serious bugs by using a global. Just use an instance variable instead @ or better yet create a method on ApplicationController called current_account which access the @current_account instance variable.

If theres not too many overrides then just put the if in the redirect filter

if action != disabled redirect() end

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top