Skip to content

Instantly share code, notes, and snippets.

@lettas
Last active December 3, 2018 07:32
Show Gist options
  • Save lettas/4442121 to your computer and use it in GitHub Desktop.
Save lettas/4442121 to your computer and use it in GitHub Desktop.
Railsでマスターデータの管理にCSVを使うときのseeds.rb
require 'csv'
Dir.glob('db/seeds/*.csv') do |file|
puts file
table_name = file.gsub(/^.*\/([\w\d_]+)\.csv/, '\1')
model_class = Module.const_get(table_name.classify)
models = CSV.read(file, headers: true).collect{|r| model_class.new(r.to_hash)}
update_columns = model_class.accessible_attributes.to_a.reject{|s| s.empty?}
model_class.record_timestamps = false if %w(created_at, updated_at).any?{|t| update_columns.include?(t)}
ActiveRecord::Base.clear_active_connections!
model_class.import models, on_duplicate_key_update: update_columns
end
@lettas
Copy link
Author

lettas commented Jan 3, 2013

必要なモジュール

gem 'activerecord-import'

使い方

  1. ヘッダ行にカラム名を持ったCSVを作成する。
  2. db/seeds/以下に「テーブル名.csv」というファイル名で配置する。
  3. コマンド rake db:seed を実行する。

@lettas
Copy link
Author

lettas commented Jan 3, 2013

メモ

データを入れ直したいときは以下のコマンド。

rake db:reset
rake db:seed

※全部のテーブルの中身が消えるから本番環境では使えない。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment