Search code examples
ruby-on-railsruby-on-rails-3mongoidactivemodelmongoid3

Allow blank dates to pass validation and save in the database?


I have a Rails app, I am using Mongoid driver to map to my Mongodb database. I would like to allow users to not specify their date of birth if they do not want to. If they do specify the date I would like the validation of the applicable years to apply.

I have the code below in my model:

field :date_of_birth, type: Date

validates_date :date_of_birth, :before => lambda { 6.years.ago }, :before_message => 'must be at least 6 years old',
                 :on_or_after => lambda { 70.years.ago }, :on_or_after_message => 'please enter a valid date of birth'

How do I allow users to save a blank date that passes validation and saves to the database. I get the following error when I pass a blank date with the current code:

Date of birth translation missing: attributes.date_of_birth.invalid_date


Solution

  • Like this:

    validates_date :date_of_birth,
      :unless => 'date_of_birth.blank?',
      :before => lambda { 6.years.ago },
      :before_message => 'must be at least 6 years old',
      :on_or_after => lambda { 70.years.ago },
      :on_or_after_message => 'please enter a valid date of birth'
    

    And you probably shouldn't block people over 70 years old like that :)