Refactoring before_filters in a controller

I'm working on a rails app that has a whole bunch of pre-filters in user_controller looking for custom roles provided by Acts as State Machine. They look something like this:

class UsersController < ApplicationController

before_filter :not_logged_in_required, :only => [:new, :create]
before_filter :find_user_or_current_user, :only => [:edit, :update]
before_filter :find_user, :only => [:suspend, :unsuspend, :destroy, :purge]
before_filter :admin_required, :only => [:suspend, :unsuspend, :destroy, :purge]
before_filter :check_administrator_role, :only [:index, :suspend, :destroy, :purge]

      

With all the state checking for every action monitored by the UserController, performance becomes an issue, and SQL queries against the Users column take up to 5ms on my machine.

I'm guessing all of these filters play a role in drag and drop performance, and I'm wondering how best to refactor them to improve reading from the database.

0


source to share


1 answer


Explain the many privileges in your user model (flags maybe? Full Privilege model and linktable might be overkill, but maybe not). Store the current user id (and maybe a couple of other commonly used things) per session. Leave one before_filter called :auth

, which executes User.find(session[:user_id])

and sets some known class variable, perhaps @loggedinuser

for the User object. Then you search in @loggedinuser

for privileges.



+1


source







All Articles