【发布时间】:2012-11-09 04:38:14
【问题描述】:
我正在尝试将日期“03/20/1985”输入到名为“生日”的文本字段中,并将其插入到列类型为“日期”的数据库字段中。
当我输入10/20/1985 时,我收到错误“生日无效”,但当我输入20/10/1985 时,它工作得很好。
从我一直阅读的所有文档来看,chronic 应该将“10/20/1985”解析为 mm/dd/yyyy,但它似乎将其解析为 dd/mm/yyyy。
我怎样才能将日期解析为 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
【问题讨论】:
-
数据库中的值是什么样的?
-
如果我使用 '20/10/1985`,数据库显示
2012-10-20,但如果我使用10/20/1985,数据库不会更新任何内容,我会收到错误消息。 -
不确定是否重要,但这是一个设计模型
-
我只是想知道数据库表的构造是否奇怪,或者其他什么,但它似乎是合法的......
-
你在用 i18n 做什么吗?
标签: ruby-on-rails ruby ruby-on-rails-3 chronic