khedaywi
khedaywi

Reputation: 101

Rails CSV Import Causing Numbers with Leading 0 to Mess Up

I've wrote the code to import addresses via an uploaded CSV file that sometimes includes postal codes that have a leading 0.

The problem is that the postal codes that have a leading 0 are not imported properly. For example, an address that was imported with a postal code of 02420 ultimately is saved to the db at 1296. Not sure what's going on. Not sure if there's a pattern that was used to convert the 02420 to 1296

Every other postal code and aspect of all addresses are import correctly.

Here's the app setup:

What I've tried:

Thanks for the help!

Upvotes: 0

Views: 1542

Answers (2)

khedaywi
khedaywi

Reputation: 101

Okay, so I figured it out. Somewhere along the way it had to be converting the 02420 (or any other number with a leading 0) to an octal number (thanks Melvin Kicchi)

The original code:

CSV.foreach(file.path, headers: true, skip_blanks: true, converters: :all, encoding: 'windows-1251:utf-8') do |row|

The code that fixed the conversion:

CSV.foreach(file.path, headers: true, skip_blanks: true, encoding: 'windows-1251:utf-8') do |row|

Needed to remove the converters: :all, since the parser was converting all different types of data and therefore passing the 02420 as an integer, which later became an octal number.

Thanks for the help! Correct me if my understanding is wrong.

You can read more about Ruby's CSV Converters

Upvotes: 3

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8132

try this

 student.addresses.create(
      line1: row["address_line1"],
      line2: row["address_line2"],
      line3: row["address_line3"],
      city: row["address_city"],
      state: row["address_state"],
      postal: row["address_postal"].try(:to_s),
      country: row["address_country"],
      kind: row["address_address_kind"]
    )

Upvotes: 0

Related Questions