Skip to content

Instantly share code, notes, and snippets.

@jasdeepsingh
Created November 3, 2011 00:07
Show Gist options
  • Save jasdeepsingh/1335381 to your computer and use it in GitHub Desktop.
Save jasdeepsingh/1335381 to your computer and use it in GitHub Desktop.
User Model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :lockable, :timeoutable, :confirmable and :activatable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :token_authenticatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation
# Self defined attributes.
# The below attribute (:user_role) is used in the before_save callback
#attr :user_role
# Associations
has_and_belongs_to_many :roles
has_many :stores, :foreign_key => "merchant_id"
has_many :deals, :foreign_key => "merchant_id"
has_many :punches, :foreign_key => "user_id"
# Callbacks
# ensure_authentication_token is a method available in the devise gem
before_save :ensure_authentication_token
after_create :add_user_role
# Function to set actual User Role before sign up
def add_user_role
user_role = Role.find_by_name(self.user_role.to_s.capitalize)
self.roles << user_role
end
# Methods for this class
def role?(role)
return !!self.roles.find_by_name(role.to_s.camelize)
end
# Method: merchant - allows me to refer to the user model as merchant
def merchant
if self.role?(merchant)
self
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment