Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to validate Dates in Rails 3? And why does validate see Date instead of String
    text
    copied!<p>I'm trying to write a date validator. The problem I'm having is that my validator sees the date_of_birth as a Date object, but it's getting set as a String. (1) why is it seeing it as a Date instead of a String before validation applies and (2) what should I do to get it to read it as a String instead of a Date. The problem I'm having is that I want to accept <code>%m/%d/%Y</code> dates, but when I enter in 07/05/2010, I get it converted to a Date, where it sees 05 as as the month and 07 as the date. I'm using Devise, so I'm not sure if it's doing something to the dates in the controller, which I doubt.</p> <pre><code>class User &lt; ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :first_name, :last_name, :password, :password_confirmation, :remember_me, :address, :date_of_birth, as: [:default, :admin] attr_accessible :active, :role, as: [ :admin ] validates_presence_of :email, :first_name, :last_name, :address validate :valid_date_of_birth def date_of_birth=(date_of_birth) Rails.logger.info("set date_of_birth: #{date_of_birth}") Rails.logger.info("set date_of_birth class: #{date_of_birth.class}") self[:date_of_birth] = date_of_birth end private def valid_date_of_birth Rails.logger.info "the date of birth: #{date_of_birth}" Rails.logger.info "the date of birth class: #{date_of_birth.class}" errors.add(:date_of_birth, 'must be a valid datetime') if ((DateTime.strptime(date_of_birth, "%m/%d/%Y") rescue ArgumentError) == ArgumentError) end end </code></pre> <p>So, setting the date_of_birth, I get String. <code>valid_date_of_birth</code> sees it as Date, which is the DB type of date_of_birth. Am I doing something wrong here that is making this overly complicated? Is my only option to maintain an additional String field? How does this work w/ edits?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload