1

好的,我以某种方式得到了一个带有日期的函数的错误:

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
4

1 回答 1

2

您正在尝试Date使用无效参数实例化对象,例如

Date.new(2013,99,1)
# => ArgumentError: invalid date

您的问题很可能不是上面提供的代码,而是您插入的数据。检查您的数据库中是否有日期无效的记录。

当日期无效时,您可以通过在提交时向用户显示错误来防止此类错误。为了实现这一点,您可以向模型添加验证规则,例如

class Patient < ActiveRecord::Base
  validate :birthday, if:->(d){ Date.valid_date?(d) }
end
于 2013-09-19T19:08:15.313 回答