Ruby on rails [Rails]不使用密码更新';更新用户信息
我执行了以下代码Ruby on rails [Rails]不使用密码更新';更新用户信息,ruby-on-rails,devise,Ruby On Rails,Devise,我执行了以下代码 @user = User.find(current_user.id) successfully_updated = if needs_password?(@user, params) @user.update_with_password(params[:user]) else # remove the virtual current_password attribute update_without_password # doesn't know how to
@user = User.find(current_user.id)
successfully_updated = if needs_password?(@user, params)
@user.update_with_password(params[:user])
else
# remove the virtual current_password attribute update_without_password
# doesn't know how to ignore it
params[:user].delete(:current_password)
@user.update_without_password(params[:user])
end
if successfully_updated
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case his password changed
sign_in @user, :bypass => true
redirect_to after_update_path_for(@user)
else
render "edit"
end
但在不使用密码的情况下更新\u,并给出false
,数据库将回滚。
我必须在没有密码的情况下进行更新吗?我刚刚解决了自己的问题。下面的代码应该像广告中所宣传的那样工作(可以在Desive的wiki页面上找到) 确保还为“需要密码”定义了私有方法
def needs_password?(user, params)
(params[:user].has_key?(:email) && user.email != params[:user][:email])
|| !params[:user][:password].blank?
end
我的问题是,我已经从“edit.html.erb”文件的表单中删除了“email”字段,因此“needs_password?”方法一直返回true,因为user.email永远不等于nil。为了解决这个问题,我添加了一个检查params[:user]。has_key?(:email)
,以查看散列中是否存在“email”
FWIW,“update_without_password”与“update_without_password”的工作原理基本相同,只是它在调用对象上的“update_attributes”之前去掉了“password”和“password_confirmation”参数,因此您不必再做任何事情。试着往上游看一看,看看你是否真的在调用“无密码更新”
def needs_password?(user, params)
(params[:user].has_key?(:email) && user.email != params[:user][:email])
|| !params[:user][:password].blank?
end