好吧我以某种方式得到一个带日期的函数的错误:
C:/geburtstag/app/config/initializers/update_year.rb:11:in `new': invalid date (
ArgumentError)
from C:/geburtstag/app/config/initializers/update_year.rb:11:in `block i
n <top (required)>'
代码如下所示:
Patient.all.each do |f|
if (f.birthday.get_birthday + 1) != f.year
f.update_attribute :year, f.birthday.get_birthday + 1
end
if f.thisyear.blank?
f.update_attribute :thisyear, Date.new(Date.today.year, f.birthday.month, f.birthday.mday )
end
if f.thisyear.year != Date.today.year
f.update_attribute :thisyear, Date.new(Date.today.year, f.birthday.month,f.birthday.mday)
end
end
第11行:
f.update_attribute :thisyear, Date.new(Date.today.year, f.birthday.month, f.birthday.mday )
我不知道为什么我会收到此错误!所以我在控制台做了一些测试,一切正常!我希望你能帮帮我!感谢
irb(main):005:0> c = Patient.find(24367)
←[1m←[36mPatient Load (0.0ms)←[0m ←[1mSELECT "patients".* FROM "patients" WHE
RE "patients"."id" = ? LIMIT 1←[0m [["id", 24367]]
=> #<Patient id: 24367, vorname: "Hanz", nachname: "Schnitzel", birthday: "1961-06
-29", geschlecht: "1", drucken: nil, extraanrede: nil, extratext: nil, year: nil
, rund: nil, thisyear: nil, zuletzt: nil, strasse: "Lsu 15", ort: "W÷rth", pl
z: "93386", created_at: "2013-09-19 16:37:28", updated_at: "2013-09-19 16:37:28"
>
irb(main):006:0> b = Patient.birthday
irb(main):007:0> d = c.birthday
=> Thu, 29 Jun 1961
irb(main):009:0> month = d.month
=> 6
irb(main):010:0> day = d.mday
=> 29
irb(main):011:0> year = Date.today.year
=> 2013
irb(main):012:0> neu = Date.new(year,month,day)
=> Sat, 29 Jun 2013
答案 0 :(得分:2)
您正尝试使用无效参数实例化Date
对象,例如
Date.new(2013,99,1)
# => ArgumentError: invalid date
您的问题很可能不是上面提到的代码,而是您插入的数据。检查数据库中是否有无效日期的记录。
您可以通过在日期无效时向用户提交错误来防止此类错误。为了实现这一点,您可以向模型添加验证规则,例如
class Patient < ActiveRecord::Base
validate :birthday, if:->(d){ Date.valid_date?(d) }
end