Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional validation based on column which may be nil

I am attempting to do a conditional validation in a active record model.

Basically, I am attempting is presence_of date should be there if the bill_due_amount is greater than zero else if bill_due_amount== zero then validation of date is not required. right now I can think of this.

validates_presence_of :next_fup_date, :if => :check_due_amount_of_bill

def check_due_amount_of_bill
  self.bill_due_amount >= 1
end

I am getting the error as

undefined method `>=' for nil:NilClass

How exactly can I do this conditional validation?

like image 313
bharath Avatar asked Dec 17 '25 22:12

bharath


1 Answers

The problem is that bill_due_amount is nil. So in your method you have to check for nil first and then >= 1:

def check_due_amount_of_bill
  self.bill_due_amount.present? && self.bill_due_amount >= 1
end
like image 158
Mischa Avatar answered Dec 19 '25 13:12

Mischa



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!