Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5: Adding conditional custom validations

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
like image 540
David B. Avatar asked Jun 01 '26 22:06

David B.


1 Answers

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?
like image 90
Andrey Deineko Avatar answered Jun 05 '26 01:06

Andrey Deineko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!