linkyndy
linkyndy

Reputation: 17900

Rails validation not failing

I have the following validation on a model field:

validates :invoice_date, :presence => true, :unless => Proc.new { |invoice| invoice.invoice_date.future? }

It looks pretty simple, but it doesn't work. There is no error thrown if the date is in the future. And the Proc indeed returns false in that case.

Any idea why isn't there any validation error shown?

Upvotes: 0

Views: 126

Answers (3)

Ajay
Ajay

Reputation: 4251

validates :invoice_date, :presence => true
validate :is_future_invoice_date?

private
 def is_future_invoice_date?
   if invoice_date.future?
     errors.add(:invoice_date, 'Sorry, your invoice date is in future time.')
   end
end

Presence true simply ensures, invoice_date must be present. for validating whether the date is a future date or not we have specified a custom validation method.(is_future_invoice_date?) This method, will add error message against our invoice_date attribute if the date is of future date.

More info here: http://guides.rubyonrails.org/active_record_validations.html#custom-methods

Upvotes: 2

Shamsul Haque
Shamsul Haque

Reputation: 2451

Try like that :--

validate check_invoice_date_is_future

def check_invoice_date_is_future
 if invoice_date.present?
   errors.add(:invoice_date, "Should not be in future.") if invoice_date.future?
 else
   errors.add(:invoice_date, "can't be blank.")
 end
end

Upvotes: 0

Mike Campbell
Mike Campbell

Reputation: 7978

The 'unless' condition is for deciding if the validation should run or not, not if it should succeed or fail. So your validation is essentially saying "validate the presence of invoice_date, unless invoice_date is in the future in which case don't validate its presence" (which makes no sense)

It sounds like you want two validations, presence and date fencing.

validate :invoice_date_in_past

def invoice_date_in_past
  if invoice_date.future?
    errors.add(:invoice_date, 'must be a date in the past')
  end
end

Upvotes: 3

Related Questions