简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM