我試圖更新配置文件頁面上的用戶密碼。爲了給您提供上下文,用戶將在其個人資料頁面上點擊「更改密碼」鏈接,該鏈接將顯示一個模式,其中包含bootstrap_form_for要求確認舊密碼,輸入新密碼以及確認新密碼。Ruby on Rails在配置文件頁面上使用Modal更改/更新密碼驗證舊密碼,添加新密碼,確認新密碼
目前,我有方法通過成功,但數據庫中的密碼沒有被改變。我沒有使用Devise,這是從頭開始的。
理想情況下,我想確保舊密碼被正確驗證,然後在數據庫中更新新密碼。
我在用戶控制器中留下了一些註釋掉的代碼,以便您可以看到我一直在嘗試的一些內容。
請指教!謝謝!
路線
resources :users do
member do
get :confirm_email
end
end
get 'change_password' => 'users#change_password'
patch 'change_password' => 'users#change_password'
用戶控制器:
def update
@user = User.find(@current_user)
User.update(@user, edit_user_params)
@user.save
redirect_to user_path
end
def change_password
@user = User.find(@current_user)
current_password = params[:user][:current_password]
user = User.authenticate(@user.email, current_password)
if @user && user
# @user.update.password = params[:new_password]
# new_password = params[:password]
# @user.update(new_password)
User.update(@user, change_password_params)
@user.save
flash[:success] = "Password successfully changed!"
redirect_to user_path(@current_user)
else
flash[:danger] = "Your old password was incorrect. Please try again."
redirect_to user_path(@current_user)
end
end
private
def user_params
params.require(:new_user).permit(:name,:email,:password)
end
def edit_user_params
params.require(:user).permit(:name,:email,:password,:city,:state_id,:country_id,:about)
end
def change_password_params
params.require(:user).permit(:password)
end
edit.html.erb(模態部分)
<!-- Change Password Modal -->
<div id="changepasswordmodal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="">Change Password</h3>
</div>
<div class="modal-body">
<%= bootstrap_form_for @user, url: change_password_path do |p| %>
<%= p.password_field :current_password, hide_label: true, placeholder: "Enter your Old Password", class: "input-lg required" %>
<%= p.password_field :password, hide_label: true, placeholder: "Enter a New Password", class: "input-lg required" %>
<%= p.password_field :password_confirmation, hide_label: true, placeholder: "Confirm New Password", class: "input-lg required"%>
<%= p.submit "Change Password", :class=> "btn btn-primary" %>
<% end %>
</div>
</div>
</div>
</div>
用戶模型(相關僅部分)
class User < ActiveRecord::Base
has_secure_password
before_create :confirmation_token
belongs_to :state
belongs_to :country
belongs_to :account_type
has_many :authentications
validates :email,
presence: true,
uniqueness: {case_sensitive: false},
format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
validates :password,
presence: true,
:on => :create
def self.authenticate email, password
User.find_by_email(email).try(:authenticate, password)
end
end
完美!謝謝! – user4889724
不客氣。 :) – akbarbin