Devise: Restricting Actions to Administrators

Trent Scott picture Trent Scott · Apr 26, 2011 · Viewed 8.6k times · Source

Following the guide here, I added a boolean attribute to my database using a migration:

rails generate migration add_admin_to_user admin:boolean

I've configured my account to be an admin (admin = 1) via Rails console. I have a controller that I want to restrict access to certain actions (new, edit, create, and destroy) for administrators only.

I'll also have normal users, I just want to restrict access to these actions for admins only in this controller. Currently, I'm using the code:

before_filter :authenticate_user!, :only => [:new, :edit, :create, :destroy]

Which restricts access to registered users -- how do I take this a step further and require admins?

Answer

Will Ayd picture Will Ayd · Apr 26, 2011

you can easily implement your own before_filter to allow access to only admin users by using the .admin? method associated with your user model. for instance:

before_filter :verify_is_admin

private

def verify_is_admin
  (current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
end