Last active
December 3, 2018 07:32
-
-
Save lettas/4442121 to your computer and use it in GitHub Desktop.
Railsでマスターデータの管理にCSVを使うときのseeds.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
メモ
データを入れ直したいときは以下のコマンド。
※全部のテーブルの中身が消えるから本番環境では使えない。