我目前在ruby on rails上编程与设计gem。添加了一个出生日期,我的用户,我试图验证用户是超过18岁。我试过了,但是没有用。
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
def is_older?()
(DateTime.now - :birth_date).to_i >= 6570
end
validates :birth_date, :presence =>{:if => {:is_older? =>{:message => 'You should be over 18 years old.'}}}
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
我不知道是否:presence应该在那里,但我添加了它,所以它不会显示任何错误。基本上,如果可能的话,我试图使用if语句作为验证器,这将检查用户试图注册的出生日期和今天的日期之间的差异是否高于18年。非常感谢!
您应该分别验证存在和年龄,并且您可以使用ActiveSupport::Duration
以获得更好的日期语法(例如,18.years.ago
):
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :birth_date, :presence => true
validate :validate_age
private
def validate_age
if birth_date.present? && birth_date > 18.years.ago.to_d
errors.add(:birth_date, 'You should be over 18 years old.')
end
end
end