Rails date validation freak on blank

When I have a date that can be nil, I usually end up needing the following code, which I’ve monkey patched into ActiveRecord::Base:

private
 
def string_to_date(value)
	value = case value
		when blank? then nil
		when Date then value
		else
			begin
				Date.parse(value) rescue nil
			rescue
				nil
			end
	end
end

Afterward, I simply use the awesome validates_timeliness plugin with :allow_nil => true.

Post a Comment

Your email is never shared. Required fields are marked *

*
*