Updating profile without updating password

做~自己de王妃 提交于 2019-12-11 17:25:09

问题


I want to be able to update my user information without having to have the user set a password each time they edit any other attribute.

My current validations are:

  validates :password, presence: true, length: { minimum: 8 }
  validates :password_confirm, presence: true

how can I make this conditional? It would be clever to only require these validations if the password and password_confirm attribues were in the params. I could use some idea about how to achieve this. Thanks.


回答1:


I think this should do it:

validates :password, presence: true, length: { minimum: 8 }
validates :password_confirm, presence: true, :if => Proc.new { |a| a.password_changed? || a.new_record? }

See the docs on ActiveModel::Dirty for more on the _changed? methods. There should be no problem running the presence validation on password every time you change an attribute since this will persist in the DB, so it will always pass (whereas password_confirm will not persist and thus requires a conditional).



来源:https://stackoverflow.com/questions/13437778/updating-profile-without-updating-password

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!