Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Validation :if one condition is true

On Rails 5.

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.

something like:

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

Thanks!

like image 629
Kathan Avatar asked Feb 27 '17 20:02

Kathan


2 Answers

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} 
like image 137
SteveTurczyn Avatar answered Sep 21 '22 09:09

SteveTurczyn


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.

validates :description, presence: true, if: :some_validation_check  def some_validation_check     first_step? || require_validation end 
like image 29
jaredready Avatar answered Sep 19 '22 09:09

jaredready