views:

191

answers:

3

i am working on a simple web app which has a user model and role model (among others), and an admin section that contains many controllers. i would like to use a before_filter to check that the user of the user in the session has a 'can_access_admin' flag.

i have this code in the application.rb:

def check_role @user = session[:user]

if @user.role.can_access_admin.nil? || [email protected]_access_admin render :text => "your current role does not allow access to the administration area." return end end

and then i have this code inside one of the admin controllers:

class Admin::BlogsController < ApplicationController before_filter :check_role

def list @blogList = Blog.find(:all) end end

and when i try to view the list action i get this error:

undefined method 'role' for user...

anyone know what i have to do to get the role association to be recognized in the application.rb? (note that the associations are configured correctly and the @user.role is working fine everywhere else i've tried to use it)

+6  A: 

just a guess but it seems that your session[:user] is just storing the id, you need to do:

@user = User.find(session[:user])

or something along those lines to fetch the user from the database (along with its associations).

It's good to do the above in a before filter too.

MatthewFord
+1  A: 

Is session[:user] holding the user? or the user_id? You may need a lookup before you call .role.

James Deville
+1  A: 

Also, if you're using ActsAsAuthenticated or RestfulAuthentication or their brethren you can also use the current_user method they supply.

Ian Terrell