繁体   English   中英

[Rails]update_without_password 不更新用户信息

[英][Rails]update_without_password doesn't update user info

我执行了以下代码

  @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

但是 update_without_password 给出false并且数据库被回滚。 我必须为 update_without_password 做些什么吗?

我刚刚经历了我自己的问题。 下面的代码应该像宣传的那样工作(在 Devise 的 wiki 页面上找到)。

def update    
  @user = User.find(current_user.id)
  successfully_updated = if needs_password?(@user, params)
    @user.update_with_password(params[:user])
  else
    params[:user].delete(:current_password)   
    @user.update_without_password(params[:user])
  end

  if successfully_updated
    set_flash_message :notice, :updated
    sign_in @user, :bypass => true
    redirect_to after_update_path_for(@user)
  else
    render "edit"
  end
end

确保您还为“needs_password?”定义了私有方法。

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_with_password' 的工作方式几乎相同,只是它在对对象调用'update_attributes' 之前去掉了'password' 和'password_confirmation' 参数,因此您不必再做任何事情。 尝试向上游看一下,看看您是否真的在调用“update_without_password”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM