如何使用rails 3.1中的Devise更改电子邮件地址

时间:2011-10-03 15:09:10

标签: ruby-on-rails devise

我想要一个“编辑个人资料”页面,用户可以在其中更改注册时注册的电子邮件地址。

我想要有以下过程:

  • 用户必须输入密码才能在电子邮件字段中进行更改之前进行确认。
  • 提交该页面后,用户应该收到验证邮件,就像Devise的默认注册一样。
  • 用户点击邮件上的验证令牌网址后,电子邮件更改即告完成。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我为我的网站创建了相同的流程。以下是您可以做的一个示例:

添加到config / routes.rb (注意路由可能会更好,但我之前做过这个)

scope :path => '/users', :controller => 'users' do
  match 'verify_email' => :verify_email, :as => 'verify_email'
  match 'edit_account_email' => :edit_account_email, :as => 'edit_account_email'
  match 'update_account_email' => :update_account_email, :as => 'update_account_email'
end

添加到app / controllers / users_controller.rb

def edit_account_email
  @user=current_user
end

def update_account_email

  @user=current_user
  @user.password_not_needed=true
  @user.email=params[:address]

  if @user.save
    flash[:notice]="your login email has been successfully updated."
  else
    flash[:alert]="oops! we were unable to activate your new login email. #{@user.errors}"
  end
  redirect_to edit_user_path

end

def verify_email

  @user=current_user
  @address=params[:address]

  UserMailer.confirm_account_email(@user, @address).deliver

end

应用/邮寄者/ user_mailer.rb

class UserMailer < ActionMailer::Base

  def confirm_account_email(user, address)

    @user = user
    @address = address

    mail(
    :to=>"#{user.name} <#{@address}>",
    :from=>"your name <'your_email@domain.com'>",
    :subject=>"account email confirmation for #{user.name}"
    )

  end

end

应用/视图/ user_mailer文件/ confirm_account_email.html.erb

<p>you can confirm that you'd like to use this email address to log in to your account by clicking the link below:</p>

<p><%= link_to('update your email', update_account_email_url(@user, :address=>@address)) %></p>

<p>if you choose not to confirm the new address, your current login email will remain active.