简体   繁体   中英

`new': invalid date ( ArgumentError)

Ok i somehow get this error for an function with an date:

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)>' 

The code looks like this:

 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  

Line 11:

f.update_attribute :thisyear, Date.new(Date.today.year, f.birthday.month,  f.birthday.mday )

I dont get why i get this error!! SO i made some test in the console, that all worked fine! I hope you can help me! Thanks

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

You are trying to instantiate a Date object with invalid parameters, eg

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

You problem is most likely not the code presented above, but the data you are inserting. Check your database for records that have invalid dates.

You can prevent such errors by presenting an error to the user upon submission when the date is invalid. In order to acheive that, you could add a validation rule to your model eg

class Patient < ActiveRecord::Base
  validate :birthday, if:->(d){ Date.valid_date?(d) }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM