RAILS 4 : Load Seed from TSV and CSV


At the article Rails 4 : Load Seed from TSV, I wrote about how to inject tsv seed data into your db. This time, I wrote about how to inject not only tsv, also csv seed data into your db.

Namely, I created CSV class like TSV class.

Environment

  • Ubuntu 14.04 LTS
  • Rails 4.1.8
  • Ruby 2.2.2

Usage

The usage is the same as one of the before article.

Instruction

rake seed_file:load TSV=aaa,bbb,ccc/ddd loads aaa.tsv, bbb.tsv and ccc/ddd.tsv in this order. And it requires class Aaa, Bbb and Ccc::Ddd, if you don’t write special code.

rake seed_file:load doesn’t load all files under db/seeds/xsv.

Attention

  • Locate TSV and CSV at the directory db/seeds/xsv, and name it like [snake case of the correspondent model] + “.tsv”.
  • The first line of TSV and CSVTSV should contain column names, and data should start with second line. 存在しないカラムが記述されている場合、そのカラムはデータベースに取り込まれません。 _memo という存在しない名前のカラムを作って、備考として利用することも可能です。
  • Don’t change id value which have been loaded once, if the TSV or CSV contains id. id をもとに データ の新規作成・更新を行っているので、 id が変更されると意図せぬデータができます。
  • You can’t delete data after loading.

Program

First, create task file.

The following program creates TSV and CSV object first, and read each line. It enables to load big file because it doesn’t load all TSV and CSV lines into RAM at once. In ruby, require 'csv' gives us CSV Class that can handle CSV and TSV, but I wanted hash of column name and value, and didn’t want to write TSV or CSV handling process in main procedure, so I created TSV and CSV Class.

Task Code

For the file "dir/file.csv", Dir::File class is used as the model.

And then, call it in seed.rb.

seed.rb

Please read Rails 4 : Load Seed from TSV for more information.