我想在rails上的ruby中验证当前密码,新密码和确认密码。当我点击更改密码时,它会要求输入当前,新密码和确认密码。但是当我不小心在“当前密码”和“新密码”字段中输入相同的密码时,它不应该允许它。它应该抛出一些错误信息,如“当前密码和新密码不能相同”。但实际上我不知道如何在轨道上的红宝石中做到这一点。如果你知道答案,请任何人帮助我。提前谢谢
答案 0 :(得分:2)
我会在users_controller.rb文件中的update方法中添加一个自定义行。我想它目前看起来像这样?
def update
@user = User.find(params[:id])
if @user.update(usere_params)
redirect_to @user
else
render 'edit'
end
end
我会在此文件中添加几行,并确保新密码和当前密码不相同,如果是,则返回验证错误。
def update
@user = User.find(params[:id])
if params[:user][:new_password] == prams[:user][:current_password]
@user.errors.add(:new_password, 'Can not use current password')
end
if !@user.errors.any? and @user.update(user_params)
redirect_to @user
else
render 'edit'
end
end
这会导致if !@user.errors.any? and @user.update(user_params)
为假(因为已经出现错误),只需运行render 'edit'
行(如果您按照这种方式进行设置,通常会显示验证错误)。< / p>