我有以下方法检查用户的出生日期("%d/%m/%Y"格式)至少为18。
def person_age
if person_birthdate.present?
now = Time.now.utc.to_date
begin
parsedDate = Date.parse(person_birthdate, '%d/%m/%Y')
diff = now.year - parsedDate.year
diff -= (diff.years.since(parsedDate) > now ? 1 : 0)
if diff < 18
errors.add :person_birthdate, 'You should be at least 18'
end
rescue
errors.add :person_birthdate, 'Date not valid'
end
else
errors.add :person_birthdate, 'Date not valid'
end
end
但是太多的if条件,有什么办法让它看起来更好吗?
应该使用内置的和自定义的验证。
validates :person_birthdate, presence: true
validate :check_age, if: -> { person_birthdate.present? }
private
def check_age
date = Date.parse(person_birthdate, '%d/%m/%Y')
unless d > 18.years.ago
errors.add(:person_birthdate, 'message here')
end
end
if: -> { person_birthdate.present? }
只允许在条件为true
时调用自定义验证
我想你想要的是:
validates_presence_of :person_birthdate # which will generate the "Date is required message"
和
def person_age
date = Date.parse(person_birthdate, '%d/%m/%Y')
unless d > 18.years.ago
errors.add :person_birthdate, "You should be at least 18."
end
end
Rails在某些方面是好的,但这里所有这些validate[s]
都是多余的:
def person_age
case Date.today - Date.parse(
person_birthdate, '%d/%m/%Y'
).advance(years: 18) rescue nil
when NilClass
errors.add :person_birthdate, 'Date not valid'
when -Float::INFINITY..0
errors.add :person_birthdate, 'You should be at least 18'
else puts "Allowed!"
end
end