【问题标题】:update_attribute/s() is calling callback for save passwordupdate_attribute/s() 正在调用回调以保存密码
【发布时间】:2012-04-11 01:44:23
【问题描述】:
我正在尝试从管理控制器(不是用户控制器)更新用户模型的单个属性。
在执行此操作时,我尝试了update_attribute(),但它也在更改用户密码。
我认为密码正在更改,因为我在用户模型上使用了 before_save 方法来散列密码。
update_attributes() 无法正常工作,因为它正在检查密码 presence=>true 的验证
有什么方法可以实现吗?
【问题讨论】:
标签:
ruby-on-rails
update-attributes
update-attribute
【解决方案1】:
您可以使用:if 选项设置验证条件。在我的代码中,它看起来像这样:
validates :password,
:length => { :minimum => 8 },
:confirmation => true,
:presence => true,
:if => :password_required?
def password_required?
crypted_password.blank? || password.present?
end
所以基本上,只有在数据库中的crypted_password 未设置(意味着正在创建新记录)或提供新的password 时才会运行验证。
【解决方案2】:
试试update_column(name, value),它可能会起作用。
【解决方案3】:
你可以像这样更新用户的单个属性
@user is that user whose attribute you want to update
例如用户名
@user.update_attributes(:user_name => "federe")
试一试,它只会更新一个属性..
【解决方案5】:
试试:
要绕过回调和验证,请使用:
User.update_all({:field_name => value},{:id => 1})
只是想让你知道: