module Care class Seed def self.execute Dir[File.join(Rails.root, "db", "seeds", "*.json")].sort.each do |path| table_name = path.split("/").last.gsub(".json", "").gsub(/^\d*_/, "") puts "*** Преднаполнение таблицы #{table_name} ***" items = ActiveSupport::JSON.decode(File.read(path)) table_name = table_name.gsub('dictionary_', 'dictionary/') || table_name if (items_class = table_name.classify.safe_constantize) items_class.import(items, on_duplicate_key_update: :all) else keys = items[0].keys v_keys = keys.join(",") values = items.map { |i| "(#{i.values.map { |v| "'#{v}'" }.join(",")})" }.join(",") set_keys = keys.map{|k| "#{k} = excluded.#{k}"}.join(", ") sql = "insert into #{table_name}(#{v_keys}) values #{values} on conflict (id) do update set #{set_keys}" puts sql ActiveRecord::Base.connection.execute sql end end end end end