Kyle Decot
Kyle Decot

Reputation: 20815

Rails 3 Devise Forgot Password w/ Multiple Emails

I have my Rails 3 set up w/ Devise but with a slight twist: I am storing all the users emails in a emails table and each user can have multiple emails. I am running into a problem w/ the forgot password feature. I know that I will have to override some method that Devise uses for looking for find a users email and then sending out the password reset but I don't know where to start. Any advice you can provide me with is most appreciated.

Upvotes: 0

Views: 1088

Answers (2)

Sply Splyeff
Sply Splyeff

Reputation: 81

Devise gets the email address from the model method 'email'. So if you're storing all emails in the emails table with Email model, you can define the 'email' method in your User's model and return addresses from emails table.

class User < ActiveRecord::Base
  devise :database_authenticatable, :recoverable, :rememberable, :authentication_keys => [ :login ], :reset_password_keys => [ :login ]
  has_many :emails
  ...
  def email
    emails.map{|record| record.email }
  end
end

Upvotes: 2

David
David

Reputation: 7303

See my answer to a similar question. You create a mailer overriding headers_for in Devise::Mailer to make it send to multiple emails:

def headers_for(action)
  #grab the emails somehow
  @emails = resource.emails.map{|email| email.column_name}
  if action == :reset_password_instructions
    headers = {
      :subject       => translate(devise_mapping, action),
      :from          => mailer_sender(devise_mapping),
      :to            => @emails,
      :template_path => template_paths
    }
  else
    # otherwise send to the default email--or you can choose just send to all of them regardless of action.
    headers = {
      :subject       => translate(devise_mapping, action),
      :from          => mailer_sender(devise_mapping),
      :to            => resource.default_email,
      :template_path => template_paths
    }
  end

  if resource.respond_to?(:headers_for)
    headers.merge!(resource.headers_for(action))
  end

  unless headers.key?(:reply_to)
    headers[:reply_to] = headers[:from]
  end
  headers
end

Upvotes: 0

Related Questions