3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】CSVファイルをテーブルにインポートする方法

Last updated at Posted at 2019-07-18

###CSVファイルを用意する
先頭行にテーブルに対応する項目名をセットする
※csvを自作する場合は、Excelの[CSV UTF-8(コンマ区切り)(.csv)]を選択してファイルを作ればうまくいった。

###インポート用ファイルを作成する

保存場所:[appルート]-[lib]-[tasks]-[import.rake]

import.rake
require 'csv'

# rake import:users
namespace :import do
  desc "Import lists from csv"

  task lists: :environment do
    path = File.join Rails.root, "xxxx/xxx.csv"
    puts "path: #{path}"
    list = []
    CSV.foreach(path, headers: true) do |row|
      list << {
          name: row["name"],
          yubin: row["yubin"],
          address: row["address"],
          tel: row["tel"],
          fax: row["fax"]
      }
    end
    puts "start to create prefectures data"
    begin
      List.create!(list)
      puts "completed!!"
    rescue ActiveModel::UnknownAttributeError => invalid
      puts "raised error : unKnown attribute "
    end
  end
end

参考:https://qiita.com/yoshito410kam/items/40b675760bd8a1f8e728

###ターミナルで呪文を唱える
rake [namespace] [taskname]

rake import:lists
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?