Rails - Validation :if one condition is true

Kathan picture Kathan · Feb 27, 2017 · Viewed 34.3k times · Source

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!

Answer

SteveTurczyn picture SteveTurczyn · Feb 27, 2017

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}