I would like to add a conditional custom validation to a model
Rails allows to create methods in order to create custom validations
class Invoice < ApplicationRecord
validate :expiration_date_cannot_be_in_the_past
def expiration_date_cannot_be_in_the_past
if expiration_date.present? && expiration_date < Date.today
errors.add(:expiration_date, "can't be in the past")
end
end
It also allows to create conditional validations
class Order < ApplicationRecord
validates :card_number, presence: true, if: :paid_with_card?
def paid_with_card?
payment_type == "card"
end
end
How can I mix both ?
My guess would be something like
validate :condition, if: :other_condition
But this creates a SyntaxError:
syntax error, unexpected end-of-input, expecting keyword_end
When you fix the missing closing end to opened if in expiration_date_cannot_be_in_the_past, you can have the following working:
validate :expiration_date_cannot_be_in_the_past, if: :paid_with_card?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With