I'm trying to create a form that will allow a user to change their password, but requires that they first input their old password. I followed the wiki for devise, https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-password and have the following form:
<%= f.fields_for :user_account, @user.user_account do |user_account| %>
<p>Edit password for account: <%= @user.user_account.email %></p>
<div class="field">
<%= user_account.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= user_account.password_field :current_password %>
</div>
<div class="field">
<%= user_account.label :password %>
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= user_account.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= user_account.label :password_confirmation %><br />
<%= user_account.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="actions">
<%= user_account.submit "Edit" %>
</div>
Here is the call to update in my user controller:
def update
respond_to do |format|
if @user.update_with_password(user_params)
sign_in @user, :bypass => true
format.html { redirect_to user_path(@user) }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
However, I'm getting an undefined method `update_with_password' for user error. devise was added to the model user_account - could it be that user does not have access to the devise method for updating with password? Is there a way around this?
You can change into:
def update
respond_to do |format|
if @user.update(user_params)
sign_in @user, :bypass => true
format.html { redirect_to user_path(@user) }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
It will validate your old password. I hope this work.
First, get the current_user.id of user then, in Devise gem, you can use update_with_password method to ask the current password and using strong parameter.
Its works on rails 4 and 5.
def update
@user = User.find(current_user.id)
respond_to do |format|
if @user.update_with_password(password_params)
sign_in @user, :bypass => true
format.html { redirect_to user_path(@user) }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
private
def password_params
params.require(:user).permit(:password, :password_confirmation, :current_password)
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.