Rails - 验证:如果一个条件为真 [英] Rails - Validation :if one condition is true

查看:36
本文介绍了Rails - 验证:如果一个条件为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 5 上.

On Rails 5.

我有一个带有 description 属性的 Order 模型.如果满足两个条件之一,我只想验证它的存在:如果当前步骤等于第一步或如果 require_validation 等于 true.

I have an Order model with a description attribute. I only want to validate it's presence if one of two conditions is met: if the current step is equal to the first step OR if require_validation is equal to true.

我可以根据这样的一个条件轻松验证:

I can easily validate based on one condition like this:

validates :description, presence: true, if: :first_step?

def first_step?
 current_step == steps.first
end

但我不确定如何添加另一个条件并验证一个或另一个是否为真.

but I am not sure how to go about adding another condition and validating if one or the other is true.

类似:

validates :description, presence: true, if: :first_step? || :require_validation

谢谢!

推荐答案

您可以对 if: 子句使用 lambda 并执行 or 条件.

You can use a lambda for the if: clause and do an or condition.

validates :description, presence: true, if: -> {current_step == steps.first || require_validation}

这篇关于Rails - 验证:如果一个条件为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆