Blank DateTime versus Nil DateTime

Hi!
These days I have been having trouble with a test that tried to test
DateTime functionality. I have discovered that a NULL DateTime is
auto-type casted to NIL by Rails.
My problem here is that I have a field :datetime and I want to allow
NULL datetimes but not wrong datetimes. With this validation if deadline
is wrong or if is is blank it returns true. How I can accomplish this?

protected
def validate
  if deadline.to_s.blank?
    true
  else
    begin
      dt = DateTime.parse(deadline.to_s)
      rescue ArgumentError
        errors.add(:deadline, "Deadline has invalid syntax")
      end
  end
end

def validate
    deadline_str = deadline_before_typecast
    unless deadline_str.blank?
        begin
           DateTime.parse(deadline_str)
           rescue ArgumentError
               errors.add(:deadline, "Deadline has invalid syntax")
           end
     end
end

Note that the return value of the validate method isn't used, what
counts is whether the model has any errors after all of the
validations have been run.

You could also attack it without overriding validate:

validate_each :deadline, :if=>lambda{|record| !
record.deadline_before_typecast.blank?} do |record, attr, value|
  DateTime.parse(deadline_before_typecast)
  rescue ArgumentError
    errors.add(:deadline, "has invalid date syntax")
  end
end

Rick Denatale wrote:

def validate
    deadline_str = deadline_before_typecast
    unless deadline_str.blank?
        begin
           DateTime.parse(deadline_str)
           rescue ArgumentError
               errors.add(:deadline, "Deadline has invalid syntax")
           end
     end
end

How can I access to the variable before the typecast? At the validate
method beginning I think the variable is already typecasted and
converted to nil.

Uh, just like Rick said. deadline_before_typecast give you the attribute "deadline" in its original format (which is often a string).

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com