Skip to content

Instantly share code, notes, and snippets.

@delba
Last active December 15, 2015 21:19
Show Gist options
  • Select an option

  • Save delba/5325356 to your computer and use it in GitHub Desktop.

Select an option

Save delba/5325356 to your computer and use it in GitHub Desktop.
Login with email or username
<%= form_tag :login do %>
<%= label_tag :login, "Email or Username" %>
<%= text_field_tag :login %>
<%= submit_tag "Log In" %>
<% end %>
class SessionsController < ApplicationController
def create
user = User.find_by_login(params[:login])
if user.try(:authenticate, params[:password])
session[:user_id] = user.id
redirect_to root_url
else
flash.now.alert = 'Wrong login/password combination'
render :new
end
end
end
class User < ActiveRecord::Base
has_secure_password
validates_presence_of :username, :email
validates_uniqueness_of :username, :email
before_save ->{ email.downcase! }, if: :email_changed?
before_save ->{ username.downcase! }, if: :username_changed?
def self.find_by_login(login)
column = login =~ /@/ ? :email : :username
find_by(column => login.downcase)
end
# before_validation :format_logins
# def self.find_by_login(login)
# where(
# "#{table_name}.email = :login OR
# #{table_name}.username = :login",
# login: login.downcase
# ).take
# end
# def self.find_by_login(login)
# login.downcase!
# where(
# arel_table[:email].eq(login).or
# arel_table[:username].eq(login)
# ).take
# end
# private
# def format_logins
# downcase_email if email_changed?
# downcase_username if username_changed?
# end
# def format_logins
# [:email, :username].each do |login|
# public_send("#{login}=", public_send(login).downcase) if public_send("#{login}_changed?")
# end
# end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment