Skip to content

Instantly share code, notes, and snippets.

@larsthegeek
Forked from kulbirsaini/devise.rb
Created September 15, 2011 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save larsthegeek/1219920 to your computer and use it in GitHub Desktop.
Save larsthegeek/1219920 to your computer and use it in GitHub Desktop.
Devise configuration to allow username or email address for sign_in, confirmation, unlock, forgot password instructions.
################################################################
# For views/migrations etc. check http://tinyurl.com/3xfx3zm #
################################################################
# File : RAILS_APP/config/initializers/devise.rb
# Change the following only. Rest can stay same
# NOTE : You must use devise master or any version released after Mar 13, 2011 to get everything mentioned here working.
config.authentication_keys = [ :login ]
config.confirmation_keys = [ :login ]
config.unlock_keys = [ :login ]
###############################################################
# IMPORTANT: You need meta_where gem for where clause to work #
# Tinker accordingly if you don't want to use meta_where #
###############################################################
# File : RAILS_APP/app/models/user.rb
# Your user model. Select appropriate model depending on your devise config
# To facilitate username or email login
attr_accessor :login
# Setup accessible (or protected) attributes for your model
# NOTE the :login here.
attr_accessible :login, :username, :email, :password, :password_confirmation, :remember_me
# Essential functions
protected
def self.find_for_database_authentication(conditions)
login = conditions.delete(:login)
where(conditions).where({:username => login} | { :email => login}).first
end
def self.find_or_initialize_with_errors(required_attributes, attributes, error=:invalid)
case_insensitive_keys.each { |k| attributes[k].try(:downcase!) }
attributes = attributes.slice(*required_attributes)
attributes.delete_if { |key, value| value.blank? }
if attributes.size == required_attributes.size
if attributes.has_key?(:login)
login = attributes.delete(:login)
record = find_record(login)
else
record = where(attributes).first
end
end
unless record
record = new
required_attributes.each do |key|
value = attributes[key]
record.send("#{key}=", value)
record.errors.add(key, value.present? ? error : :blank)
end
end
record
end
def self.find_record(login)
where({:username => login} | { :email => login}).first
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment