初期データをCSVから投入する

ユーザーに初期データをつくってもらうことも考えて、CSVからとりこめるようにしました。

準備

初期データCSVをつくり、/db下に置いておきます。

db/seed.rb

こんな感じ。

require "csv"

connection = ActiveRecord::Base.connection
tables = %w(table1 table2 table3)

tables.each do |table|
  # テーブルをTruncateする
  connection.execute("TRUNCATE #{table}") unless table == "schema_migrations"
end

items = CSV.table("db/items.csv", encoding: "Windows-31J:UTF-8")
items .each do |item|
  Item.create(
    code: item[:code],
    name: item[:name],
    birthday: ItemUtil.strfdbdate(item[:birthday]) # lib/item_util.rbのstrfdbdateメソッドで"%Y-%m-%d"に整形してる
  )
end

取り込み

$ bundle exec rake db:seed RAILS_ENV=production