一个想法是在您的编辑表单中显示密码,因为您允许空白提交属性,因此它们仅在存在时更新。
你也没有说明你是否使用gem "devise",因为这会改变我在下面写的内容。
如果你真的想做第二个视图,这里有一些帮助:
在 routes.rb 中,您需要一个新路由来显示仅包含密码的表单。
resources :users do
member do
get :edit_password
put :update_password
end
end
在您的 users_controller.rb 中添加以下方法:
def edit_password
@user = User.find(params[:id])
end
def update_password
user = User.find(params[:id])
# also in here i'm calling the authenticate method that usually is present in bcrypt.
if user and user.authenticate(params[:old_password])
if params[:password] == params[:password_confirmation]
user.password = BCrypt::Password.create(params[:password])
if user.save!
redirect_to edit_password_url, notice: "Password changed"
end
else
redirect_to edit_password_url, notice: "Incorrect Password."
end
else
redirect_to edit_password_url, notice: "Incorrect Password."
end
end
注意:在 update_password 方法中,我使用的是 bcrypt gem 中存在的身份验证。建议使用它。在此处阅读更多信息:http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html
# in Gemfile
gem 'bcrypt', '~> 3.1.7'
新建文件views/users/edit_password.html.erb并添加如下代码:
<%= form_for @user, url: update_password_user_path(@user) do |f| %>
<%= f.label :old_password %>
<%= f.password_field :old_password %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
<%= f.submit "Update password" %>
<% end %>