Reputation: 18843
When modifying Active Record object's attributes (like Task.update date: '2015-01-01'
), I'd like to know when the value is invalid ('2015-01-32'
or 'whatever'
). Right now, activerecord
just writes nil
in case of those, not very friendly I must say. Previous value is lost. I'd like to leave it there, if user inputted nothing like date.
Is there any more sensible way to figure it out than the following?
if ActiveRecord::Attribute.from_user('date', '2015-01-32', ActiveRecord::Type::Date.new).value
puts 'valid date'
end
P.S. Just in case someone wants to know how type casting happens.
Upvotes: 1
Views: 64
Reputation: 18843
If there's no way to tell activerecord
to not discard values, and no public interface for checking if a date is valid, than the best option must be to use validation:
class Task < ActiveRecord::Base
validates_date :date
end
Upvotes: 1
Reputation: 11137
you can try to parse it and when it raise error then its nit valid:
valid = Date.parse('2015-01-30').present? rescue false # true
valid = Date.parse('2015-01-32').present? rescue false # false
Upvotes: 0