问题
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