How to change email address with Devise on rails3.1
I'd like to have an "edit profile" page, in which the user can change the email address registered when signing up.
I'd like to have the following process:
- the user has to input his password to confirm before he makes changes in the email field.
- after submitting that page, the user sh开发者_运维知识库ould receive a verification mail just like Devise's default sign up.
- the email change is completed as soon as the user clicks the verification token URL on the mail.
How would I do this?
I created this same flow for a site of mine. Here's an example of what you can do:
add to config/routes.rb (note that the routing could be better, but I did this a while ago)
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
add to 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
app/mailers/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
app/views/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.
精彩评论