Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Richard Duffy
16,488 PointsAdd an attribute to devise.
Hey,
I would like to add an Admin attribute to devise, this will have to be a boolean value so does anyone have any ideas? :). This is a commercial project so if you give me any code I would need to know whether I can use it. (Just an insurance thing!).
2 Answers

Michael Hall
Courses Plus Student 30,909 PointsI did this for a user resource like this:
in my schema file my user table is defined as``` create_table "users", force: true do |t| t.string "name", null: false t.string "email", null: false t.string "password_digest", null: false t.boolean "admin", default: false end
in my user model I have a predicate method is_admin? I also use validations to insure admin has a value.
class User < ActiveRecord::Base
has_secure_password validates :password, presence: true validates :email, presence: true, uniqueness: true validates :admin, :inclusion => {:in => [true, false]}
def is_admin? self.admin == true end
end
I also use a method in my sessions controller to define current user:
module SessionsHelper
def log_in(user) session[:user_id] = user.id end
def current_user @current_user ||= User.find_by(id: session[:user_id]) end
def logged_in? current_user.present? end
def authenticate redirect_to login_path unless logged_in? end
def log_out! session[:user_id] = nil end
end
finally in controllers I have my application controller:
class ApplicationController < ActionController::Base. protect_from_forgery with: :exception
include SessionsHelper helper_method :current_user, :logged_in?, :authenticate
end
in my user controller I define authorize admin only in my private methods
def authorize_admin_only unless current_user.is_admin? redirect_to user_path(current_user) end end
def authorize_user_only unless current_user == @user redirect_to user_path(current_user) end end
def authorize_user_or_admin unless current_user == @user || current_user.is_admin? redirect_to user_path(current_user) end end
I load these methods by calling before like this:
before_action :authorize_admin_only, only: :index before_action :authorize_user_or_admin, except: [:index, :new, :create]
then when I define a method like index I set it to admin use only like this:
def index authorize_admin_only @users = User.all end
hope this helps

Richard Duffy
16,488 PointsHey,
Thanks! It does.