Search code examples
javascriptruby-on-railsrubydevisecancan

Rails: How to confirm email address entered in text box matches current user's email address?


I am creating a page that allows a user to delete their account/profile. On this page, I have a text box where the user types their email address to confirm they are indeed the current user and that they want to delete their account (upon button click).

What I want to do is, when the user clicks the "Delete Account" button below the text box, I want to grab that text and compare it to the current user's email account. If it matches, I want to delete the user's account. If not, I want to flash an error message.

I have some of the logic figured out, and I will paste what I have below. Right now, if you click the 'Delete Account' button it deletes the user's account and redirects to the home page, and flashes a 'goodbye' message on the home page. However, there is no comparison functionality b/t current user's email and text box entry. I'm not sure if I can do this in Rails or if I will have to incorporate JavaScript. I am using Devise and Cancan.

Please be as explicit as possible, I am fairly new to Rails. Thank you!

Email box and button are at /settings/profile/delete, file is 'delete.html.haml'.

The email box

.field
  = label :email, 'Email Address'
  = email_field :email, 'Enter your email address', id: 'delete-email-box'

The Delete Account Button (below email box)

#confirm-delete-btn
  = link_to 'Delete Account', user_registration_path, method: :delete, data: 
   { confirm: 'Are you sure you want to delete your account? This cannot be 
   undone!' }, class: submit btn-delete'
  = link_to 'Cancel', profile_index_path, id: 'cancel-profile'

profile_controller.rb

def delete
  @user = current_user
  @profile = current_user.profile
end

def destroy
  @user = current_user
  @profile = current_user.profile
  if @profile.destroy
    @user.destroy
    redirect_to root_url, notice: "User deleted."
  else
    render_error_message
  end
end

Solution

  • Just looked at how to make a form to delete items and found this. So your form would look like this:

    <% form_for(:user, :url => path_for_your_destroy_action(@user), :html => {:method => :delete}) do  %>
      email: <%= text_field_tag :mail %>
      <%= submit_tag "Delete" %>
    <% end %>
    

    Now inside your destory method you could simply check if email matches current users email and if it does that delete his account:

    def destroy
      if current_user.email == params[:email]
        current_user.destroy
        redirect_to your_path, notice: "user deleted"
      else
        render "your_form", notice: "invalid email"
      end
    end