発生したエラー
Encoding::CompatibilityError: incompatible character encodings: ASCII-8BIT and UTF-8
rails db:seedのコマンドを実行するとこのようなエラーとなります。
seeds.rbのファイル内はこのような記述をしています。↓↓↓
ruby
1require 'csv' 2require 'zip' 3 4DLURL = "http://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip" 5SAVEDIR = "db/" 6CSVROW_PREFNAME = 6 7CSVROW_CITYNAME = 7 8 9savePath = "" 10 11# 住所CSVダウンロード、解答し保存 12open(URI.escape(DLURL)) do |file| 13 ::Zip::File.open_buffer(file.read) do |zf| 14 zf.each do |entry| 15 savePath = SAVEDIR + entry.name 16 zf.extract(entry, savePath) { true } 17 end 18 end 19end 20 21# 住所CSVを読み込みDBに保存 22CSV.foreach(savePath, encoding: "Shift_JIS:UTF-8") do |row| 23 prefName = row[CSVROW_PREFNAME] 24 cityName = row[CSVROW_CITYNAME] 25 pref = Pref.find_or_create_by(:name => prefName) 26 City.find_or_create_by(:name => cityName, pref_id: pref.id) 27end 28 29File.unlink savePath
source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.7.0' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 6.0.3', '>= 6.0.3.1' # Use mysql as the database for Active Record gem 'mysql2', '>= 0.4.4' # Use Puma as the app server gem 'puma', '~> 4.1' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', '>= 1.4.2', require: false gem 'pagy', '~> 3.5' # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible # gem 'rack-cors' # devise関連 gem 'devise' gem 'devise_token_auth' # CORS設定 gem 'rack-cors' #ActiveModelSerializers gem 'active_model_serializers' group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] #.envを使うためのgem gem 'dotenv-rails' gem 'faker' end group :development do gem 'listen', '~> 3.2' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' gem 'pry-byebug' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
日本郵便のhttps://www.post.japanpost.jp/zipcode/dl/oogaki-zip.html
ここにある全国一括のcsvファイルを読み込みたいのですがうまくいきません。
詳しい方、教えてください!