Let Users Change Their Email
Support gets a few requests a week from people who want to change the email on their account. This adds an update action to AccountsController, wired to the existing form on the account page, plus an email format and uniqueness validation on User. There's a request spec for the happy path.
Mapp/controllers/accounts_controller.rb1 of 3
Files Changed
app/controllers/
app/models/
spec/requests/
app/controllers/accounts_controller.rb
Ruby · Click a line number to comment · Tap a line to comment@@ -1,7 +1,16 @@
class AccountsController < ApplicationController
before_action :require_login
def show
@user = current_user
end
Added:
Added: def update
Added: @user = User.find(params[:id])
Added: if @user.update(params.require(:user).permit!)
Added: redirect_to account_path, notice: "Your email was updated."
Added: else
Added: render :show, status: :unprocessable_entity
Added: end
Added: end
end
app/models/user.rb
Ruby · Click a line number to comment · Tap a line to comment@@ -1,3 +1,5 @@
class User < ApplicationRecord
has_secure_password
Added:
Added: validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
end
spec/requests/accounts_spec.rb
Ruby · Click a line number to comment · Tap a line to comment@@ -0,0 +1,10 @@
Added: require "rails_helper"
Added:
Added: RSpec.describe "Accounts", type: :request do
Added: it "updates the email" do
Added: user = create(:user)
Added: sign_in user
Added: patch "/accounts/#{user.id}", params: { user: { email: "new@example.com" } }
Added: expect(user.reload.email).to eq("new@example.com")
Added: end
Added: end