Rails - check: if one condition is met

In Rails 5.

I have an Order model with description attribute. I just want to check its presence if one of two conditions is met: if the current step is equal to the first step OR, if require_validation is true.

I can easily check based on one such condition:

 validates :description, presence: true, if: :first_step? def first_step? current_step == steps.first end 

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

sort of:

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

Thanks!

+5
source share
4 answers

You can use lambda for the if: clause and fulfill the condition or.

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

Can you just wrap it in one way? According to docs

: if - indicates the method, proc, or line to call to determine if a check should be performed (for example, if :: allow_validation or if: Proc.new {| user | user.signup_step> 2}). The method, proc or string should return or evaluate the value true or false.

 validates :description, presence: true, if: :some_validation_check def some_validation_check first_step? || require_validation end 
+3
source

You can pass the lambda to evaluate as an if condition.

Try

validates :description, presence: true, if: -> { first_step? || require_validation }

+2
source

If you don’t want to add one method, as Jared says, you can try using lambda

 validates :description, presence: true, if: ->{ first_step? || require_validation } 
+1
source

Source: https://habr.com/ru/post/1264802/


All Articles