i am wondering how you deal with date validation in your models … if i
have a date attribute it only eats date objects … so i when i do this
u = User.new(:born => Date.today)
it works, but this results in a nil value in :born attribute …
u = User.new(:born => ‘10.10.2007’)
puts(u.born) #results in nil
so now i cannot really validate dates because the string is not stored
in the attribute … whereas all other attributes store everything …
when i excpect a number in an attribute i can assign a string but the
object will stay invalid (if i have a validator)
so whats the best thing to deal with dates in connection with a web
form?
i am wondering how you deal with date validation in your models … if i
have a date attribute it only eats date objects … so i when i do this
u = User.new(:born => Date.today)
it works, but this results in a nil value in :born attribute …
u = User.new(:born => ‘10.10.2007’)
puts(u.born) #results in nil
so now i cannot really validate dates because the string is not stored
in the attribute … whereas all other attributes store everything …
when i excpect a number in an attribute i can assign a string but the
object will stay invalid (if i have a validator)
so whats the best thing to deal with dates in connection with a web
form?
I don’t think the dot notation works for dates. Hyphens and slashes are
okay though. In terms of validation, a simple trick I use is…
class User
validate :born_should_be_valid_date
protected
def born_should_be_valid_date
born.to_date
rescue
errors.add(:born, 'Invalid date for born')
end
end
The #to_date method is provided by Rails and will turn a string, Time or
Date object into a Date object if it can, and will raise an exception if
it can’t.
daniel i dont fully understand your approach … i still cannot assign
u = User.new(:born => ‘foo’)
here born will hold nil because it cannot be parsed to a date. but
normally it should keep the invalid value and indicate that the instance
is invalid …so the whole to_date stuff is not needed because i can
only assign a valid date anyway … if its not valid it sets the
attribute to nil
the thing is that i want to keep the value and show the user that the
value is invalid … like with all other attributes
the thing is that i want to keep the value and show the user that the
value is invalid … like with all other attributes
hope you understand what i mean
Mass assignment, methods like new and create (i.e. those which take a
hash of attribute names to variables appear to all nil out values
that dont match.
But if you instead did.
u = User.new
u.born = “foo” # or equivalently u[:born] = “foo”