Skip to content

Instantly share code, notes, and snippets.

@joejwright
Created July 31, 2014 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joejwright/85aa1361c01b43d61cff to your computer and use it in GitHub Desktop.
Save joejwright/85aa1361c01b43d61cff to your computer and use it in GitHub Desktop.
Devise Model w/ Token Auth
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
before_save :ensure_authentication_token
after_save :ensure_account
belongs_to :account
validates :name, :presence => true
def ensure_authentication_token
if authentication_token.blank?
self.authentication_token = generate_authentication_token
end
end
private
def generate_authentication_token
loop do
token = Devise.friendly_token
break token unless User.where(authentication_token: token).first
end
end
def ensure_account
if self.account_id.blank?
acc = Account.create(:name => self.name)
#acc.save
self.account = acc
self.save
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment