Created
March 13, 2021 14:59
-
-
Save shimadama/a39bac674fd45febe093e9b849d9c221 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment