[Rails] update_without_password不会更新用户信息。

3
我执行了以下代码。
  @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 做些什么吗?

1个回答

3

我刚经历了这个问题。下面的代码应该像Devise维基页面中所描述的那样正常工作。

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'。
顺便说一句,'update_without_password'基本上与'update_with_password'的工作方式相同,只是在调用对象的'update_attributes'之前删除了'password'和'password_confirmation'参数,所以你不需要做任何其他事情。试着往上游看看,看看你是否真的在调用'update_without_password'。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接