1

I am trying to write a method in my application controller that would be available to all the controllers. It is a simple roles thing.

def user_is_admin
    if current_user.admin == true
    end
  end 

If the current logged in user has .admin set to true than this method should return true.

Then in my controller I am doing: before_filter :user_is_admin, :only => [show]

While the code is not erroring, its also not protecting the page from being viewed.

any ideas?

3 Answers 3

1

You need the before_filter to do something to interrupt the action if the current user is not an admin.

def user_is_admin
    if current_user.admin != true
        redirect_to <some_other_action> 
        return false
    end
end 

Note that this is checking that the current_user is NOT an admin. Alternately, you could raise an exception or render an error template without redirecting:

def user_is_admin
    if current_user.admin != true
        raise "Admin required"
    end
end 

or

def user_is_admin
    if current_user.admin != true
        render :template => 'shared/admin_required'
        return false
    end
end 
1

You're asking for something different then what your code is doing.

What you would want your method to do, is something like this:

def user_is_admin
  redirect_to root_url, notice: "You do not have sufficient privileges for that!" unless current_user.admin
end

Where root_url is where they would be redirected. You still need the before_filter.

1
  • Thanks for the edit, not sure why I didn't type it like that :) Dec 22, 2011 at 2:08
0

You mean this?

def user_is_admin
  redirect_to "/" unless current_user.admin
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.