简体   繁体   中英

Rails throwing “Invalid Date”

I'm importing a csv file into pg database, and am getting this error that I never got before upgrading to Rails 5

def self.assign_from_row(row)
  member = Member.where(membership_id: row[:membership_id]).first_or_initialize
  member.assign_attributes row.to_hash.slice(
  :last_name, :first_name, :membership_id, :email
).merge(
  :birthday => row[4].nil?  ? nil : DateTime.strptime(row[4], "%m/%d/%Y").strftime("%Y/%m/%d")
)
  member
end

The exact error is with the birthday line. When I remove from .merge to ), things work. The csv headers look like this:

"Last Name","First Name","Membership Id","E-mail","Birthday"

and the rows look like this:

"Aber","Barbara","00591 2","bab@example.com","07/05/2015"

I have also tried this line

:birthday => DateTime.strptime("%m/%d/%Y").strftime("%Y/%m/%d")

I believe the problem lies in the fact that many of the birthdays are populated with "", or are nil and I don't know how to tell the database to insert nil when it is expecting a date format. Any help most appreciated

You can rescue nil if the date conversion fails.

:birthday => (DateTime.strptime(row[4], "%m/%d/%Y").strftime("%Y/%m/%d") rescue nil)

In line rescue is generally not recommended as it can mask other raised exceptions (for example, if you accidentally typed DateTim instead of DateTime you wouldn't spot the problem) but used with care, in line rescue is a useful tool.

I had to go back to the csv original, open it in Office Calc and change the cells containing the date as a string. I first changed the column to a number, then a date with a format to match the sql format '2015-02-23' and it imported just fine. Thanks everybody! So it wasn't a Rails issue to begin with, but rather the misidentification of the column. I actually had to go through some hoops in Calc to do it. I had to change the column to a number first, then to a date.

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