[Rails] update_without_password不更新用户信息 [英] [Rails]update_without_password doesn't update user info

查看:68
本文介绍了[Rails] update_without_password不更新用户信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我执行了以下代码

  @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做些什么吗?

but update_without_password give false and database is rollbacked. Do I have to do something for update_without_password?

推荐答案

我刚刚经历了自己的问题.以下代码应按广告规定运行(如Devise的Wiki页上所示).

I just went through my own issues with this. The following code should work as advertised (as found on the wiki page for 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"定义了私有方法?

Make sure you also define the private method for '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"文件中的表单中删除了电子邮件"字段,所以"needs_password?"由于user.email从不等于nil,因此方法始终返回true.为了解决此问题,我添加了一个检查 params [:user] .has_key?(:email),以查看哈希中是否存在"email".

My issue was that I had removed the "email" field from the form in the 'edit.html.erb' file, so the 'needs_password?' method kept returning true since user.email was never equal to nil. To fix the issue, I added in a check params[:user].has_key?(:email) to see if 'email' exists in the hash.

FWIW,"update_without_password"几乎与"update_with_password"相同,但在调用对象的"update_attributes"之前,它会去除"password"和"password_confirmation"参数,因此您不必这样做更多的东西.尝试向上游看一下,看看您是否真的在调用"update_without_password".

FWIW, the 'update_without_password' pretty much works the same way as 'update_with_password' except that it strips out the 'password' and 'password_confirmation' parameters before calling 'update_attributes' on the object, so you shouldn't have to do anything more. Try looking upstream a bit and see if you really are calling 'update_without_password'.

这篇关于[Rails] update_without_password不更新用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆