简体   繁体   中英

Rails validates unless

How can I have multiple unless statements? For example, in my model I have:

validates :email, unless: :guest?

But if try to have two unless methods:

validates :email, unless: (:guest? || :skip_validation)

It doesn't work. If :guest? is false but :skip_validation is true, the validation produces an error, requiring a valid email.

I got it to work by combining the :guest? and :skip_validation methods and passing that to validates, but was curious if unless: can take multiple methods?

So, you want to validate emails if !:guest || !:skip_validation if !:guest || !:skip_validation , if the user is not a guest or we do not want to skip validation. Thus the unless condition is:

unless !(!:guest? || !:skip_validation)

Using De Morgan's laws, we can simplify this to:

unless :guest? && :skip_validation

So basically we have to use an and instead of an or .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM