1
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をDBに登録する

Last updated at Posted at 2018-08-08

CSVをDBにimportする

gemのactiverecord-importを入れて、モデルのApplicationRecord.rbで下記を書く


class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
  require 'csv'

  def self.simple_import(path: '', col_sep: ',')
    a = []
    CSV.foreach(path, headers: true, col_sep: col_sep) do |r|
      a << new(get_import_params(r))
    end
    import a # activerecord-importのメソッドです。
  end

  private

  def self.get_import_params(row)
    headers = row.headers & column_names # 存在するカラム名のみに限定する
    headers.each_with_object({}) do |c, h|
      h[c.to_sym] = row.field(c)
    end
  end
end

あとは
simple_importを呼び出して終わり
例:dbディレクトリの下層にファイルを保存した場合

> モデル名.simple_import(path: 'db/ファイル名.csv', col_sep: ',')

参照記事:https://qiita.com/junara/items/183aaff5e5b77ec1c679

1
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
1
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?