[英]Rails models validation on update
I cannot figure out why my model is not behaving as I want. 我无法弄清楚为什么我的模型不符合我的要求。
class User < ActiveRecord::Base
has_secure_password
validates :first_name, :last_name,
presence:true,
length: { maximum: 30 }
validates :username,
presence:true,
uniqueness:true,
length: { maximum: 30 }
validates :password,
presence:true,
confirmation: true,
length: { :minimum => 6},
unless: lambda{ persisted? and password.nil? }
validates :password_confirmation,
presence: true,
unless: lambda{ persisted? and password.nil? }
validates :email,
format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create },
uniqueness: true,
allow_blank: true
end
As you can see the code is quite easy. 如您所见,代码非常简单。
To have a password_digest field I neeed both 'password' and 'password_confirmation'. 为了拥有password_digest字段,我选择了“ password”和“ password_confirmation”。
In create mode everything is fine. 在创建模式下,一切都很好。 In update mode is not working as I need. 在更新模式下,我无法正常工作。
I want to check validate the password and check if they match always, except when the user already exist and the 'password' field is null. 我想检查密码并检查它们是否始终匹配,除非用户已经存在并且“ password”字段为null。
Any suggestion? 有什么建议吗?
I would try a simpler logic: 我会尝试一个更简单的逻辑:
validates :password,
presence:true,
confirmation: true,
length: { :minimum => 6},
unless: :persisted?
validates :password_confirmation,
presence: true,
if: lambda{ password.present? }
For a new User
: 对于新User
:
password
is blank, you get an error on password
如果password
为空,你会得到一个错误password
password
is present and password_confirmation
is blank, you get an error on password_confirmation
如果password
存在并且password_confirmation
为空,则您会在password_confirmation
上收到错误消息 For an existing User
: 对于现有User
:
password
is blank, nothing happens 如果password
为空,则什么也不会发生 password
is present and password_confirmation
is blank, you get an error on password_confirmation
如果password
存在并且password_confirmation
为空,则您会在password_confirmation
上收到错误消息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.