[英]Rails: How to confirm email address entered in text box matches current user's email address?
我正在創建一個頁面,該頁面允許用戶刪除其帳戶/配置文件。 在此頁面上,我有一個文本框,用戶在其中輸入其電子郵件地址,以確認他們確實是當前用戶,並且希望刪除其帳戶(單擊按鈕時)。
我想做的是,當用戶單擊文本框下方的“刪除帳戶”按鈕時,我要獲取該文本並將其與當前用戶的電子郵件帳戶進行比較。 如果匹配,我要刪除該用戶的帳戶。 如果沒有,我想刷新一條錯誤消息。
我已經弄清楚了一些邏輯,我將在下面粘貼我的內容。 現在,如果您單擊“刪除帳戶”按鈕,它將刪除用戶的帳戶並重定向到主頁,並在主頁上閃爍“再見”消息。 但是,當前用戶的電子郵件和文本框輸入沒有比較功能。 我不確定是否可以在Rails中做到這一點,或者是否必須合並JavaScript。 我正在使用Devise和Cancan。
請盡可能明確,我是Rails的新手。 謝謝!
電子郵件框和按鈕位於/ settings / profile / delete,文件為'delete.html.haml'。
郵箱
.field
= label :email, 'Email Address'
= email_field :email, 'Enter your email address', id: 'delete-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
只是看着如何制作一個表格來刪除項目並發現了這一點 。 因此,您的表單將如下所示:
<% form_for(:user, :url => path_for_your_destroy_action(@user), :html => {:method => :delete}) do %>
email: <%= text_field_tag :mail %>
<%= submit_tag "Delete" %>
<% end %>
現在,在您的銷毀方法中,您可以簡單地檢查電子郵件是否與當前用戶的電子郵件匹配,並且如果這樣做,則刪除他的帳戶:
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
根據您的代碼,添加到David的答案后,您似乎也在嘗試刪除用戶的個人資料。 它沒有明確描述用戶與配置文件的關系,但是基於您如何在當前銷毀操作中設置內容,我通過某種關聯來假設用戶。 在這種情況下,您仍然需要銷毀概要文件,否則它將作為未使用的行保留在數據庫中。 這可以通過對destroy動作進行簡單的添加來實現:
def destroy
if current_user.email == params[:email]
current_user.profile.destroy
current_user.destroy
redirect_to your_path, notice: "user deleted"
else
render "your_form", notice: "invalid email"
end
end
但是,這很笨拙,將來需要在其他地方實現類似功能時,很容易導致錯誤。 在模型層使用多種DRYer Rails處理方式:
User.rb:
has_one :profile, dependent: :destroy
這將確保在銷毀用戶時,其關聯的配置文件也將自動銷毀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.