Last active
December 15, 2015 21:19
-
-
Save delba/5325356 to your computer and use it in GitHub Desktop.
Login with email or username
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <%= form_tag :login do %> | |
| <%= label_tag :login, "Email or Username" %> | |
| <%= text_field_tag :login %> | |
| <%= submit_tag "Log In" %> | |
| <% end %> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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