Ruby-on-rails Rails - 验证:如果一个条件为真
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42495133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails - Validation :if one condition is true
提问by Kathan
On Rails 5.
轨道 5.
I have an Ordermodel with a descriptionattribute. 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.
我有一个Order带有description属性的模型。如果满足两个条件之一,我只想验证它的存在:如果当前步骤等于第一步或如果 require_validation 等于 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.
但我不确定如何添加另一个条件并验证一个或另一个是否为真。
something like:
就像是:
validates :description, presence: true, if: :first_step? || :require_validation
Thanks!
谢谢!
回答by SteveTurczyn
You can use a lambda for the if:clause and do an or condition.
您可以对if:子句使用 lambda并执行 or 条件。
validates :description, presence: true, if: -> {current_step == steps.first || require_validation}
回答by jaredready
Can you just wrap it in one method? According to the docs
你能用一种方法包装它吗?根据文档
:if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. if: :allow_validation, or if: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.
:if - 指定要调用的方法、过程或字符串以确定是否应进行验证(例如,如果::allow_validation,或如果:Proc.new { |user| user.signup_step > 2 })。方法、proc 或 string 应返回或评估为 true 或 false 值。
validates :description, presence: true, if: :some_validation_check
def some_validation_check
first_step? || require_validation
end
回答by Malav Bhavsar
You can pass a lambda to be evaluated as the ifcondition.
您可以传递一个 lambda 作为if条件进行评估。
Try:
尝试:
validates :description, presence: true, if: -> { first_step? || require_validation }
回答by Alexander Kuznetsov
If you don't want to add one method as Jared say then you can try use lambda
如果您不想像 Jared 所说的那样添加一种方法,那么您可以尝试使用 lambda
validates :description, presence: true, if: ->{ first_step? || require_validation }
回答by murat
If you have a lot case , you can design for validates
如果你有很多案例,你可以设计验证
validates_presence_of :price_tech_fee, if: :price_tech_fee_require?, :message => :required
validates_presence_of :percentage_tech_fee, if: :percentage_tech_fee_require?, :message => :required
def percentage_tech_fee_require?
is_active? && is_transaction_percentage? && is_premium?
end
def is_active?
!self.is_deleted && self.is_active
end
def is_transaction_percentage?
self.is_per_transaction && self.is_percentage
end
def is_premium?
....
end

