Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a solution for Rails Gem Devise to allow a user to have multiple emails?

I'm looking for a solution to allow a user on my app to have more than 1 email. This should work similar to Facebook, LinkedIn and Quora. Where an account can have multiple emails, 1 as the primary.

Is there a turn-key solution for devise avaialble? I'm hoping to not have to write this from scratch given it's so common.

Ideas? Thanks

like image 689
AnApprentice Avatar asked Apr 29 '13 17:04

AnApprentice


People also ask

How does devise gem work?

Devise is the cornerstone gem for Ruby on Rails authentication. With Devise, creating a User that can log in and out of your application is so simple because Devise takes care of all the controllers necessary for user creation ( users_controller ) and for user sessions ( users_sessions_controller ).


1 Answers

Hm...I'll suggest to create new model, You'll do something like this:

For example model would beUserEmail.

class UserEmail < ActiveRecord::Base
    belongs_to :user
end

class User < ActiveRecord::Base
    has_many :user_emails
end

and override devise's method to find record in User model:

def self.find_first_by_auth_conditions(warden_conditions)
  conditions = warden_conditions.dup
  if email = conditions.delete(:email)
    User.includes(:user_emails).where('user_emails.email = ?', email).first
  else
    super(warden_conditions)
  end

Read more about override here: https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address

like image 77
Bob Avatar answered Oct 26 '22 18:10

Bob