ruby-on-railsrubyruby-on-rails-3chronic

Rails chronic gem not validating as expected


I'm trying to enter the date '03/20/1985' into a text field called "birthday" and have it inserted into a database field with the column type "date".

When i enter 10/20/1985, i get the error "Birthday is invalid", but when i enter 20/10/1985, it works just fine.

From all the documentation i have been reading, chronic should parse '10/20/1985' as mm/dd/yyyy, but it seems that it's parsing it as dd/mm/yyyy.

How can i make this parse the date as mm/dd/yyyy?

/models/user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]

  # Virtual attribute for authenticating by either username or email
  # This is in addition to a real persisted field like 'username'
  attr_accessor :login

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :login, :first_name, :last_name, :home_phone, :cell_phone, :work_phone, :birthday, :home_address, :work_address, :position, :company

  validate :birthday_is_date
  validate :position, :presence => true

  require 'chronic'

  # validate the birthday format
  def birthday_is_date 
    errors.add(:birthday, "is invalid") unless Chronic.parse(birthday)
  end

  # validates email or username when logging in
  def self.find_first_by_auth_conditions(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    else
      where(conditions).first
    end
  end

end

Solution

  • If the value is stored as a date in the database, Rails will coerce the value from a string to a Ruby Date on assignment. I think it probably uses the built-in Date.parse method (docs):

    Date.parse "2012-10-20"
    # => #<Date 2012-10-20 ...>
    
    Date.parse "20-10-2012"
    # => #<Date 2012-10-20 ...>
    
    Date.parse "10-20-2012"
    # => ArgumentError: invalid date
    

    This being the case, you want to avoid the coercion and get your hands on a raw string to parse with Chronic. This is an ideal use-case for virtual attributes. There are a few ways you can do it, something like this should get you started

    class User < ActiveRecord::Base
      validate :birthday_is_date
    
      # an explicit implementation
      def birthday_string
        if @birthday_string
          @birthday_string
        elsif birthday.present?
          birthday.strftime("%d-%m-%Y")
        else
          ""
        end
      end
    
      # a shorter implementation
      def birthday_string
        @birthday_string || birthday.try(:strftime, "%d-%m-%Y")
      end
    
      def birthday_string=(value)
        @birthday_string = value
        self.birthday = parse_birthday
      end
    
      private
    
      def birthday_is_date
        errors.add(:birthday_string, "is invalid") unless parse_birthday
      end
    
      def parse_birthday
        Chronic.parse(birthday_string)
      end
    end
    

    And then use birthday_string in your forms, instead of birthday.