Sha256: bc8cd8a69473ad28f831b651421377e04bae52c2a19b42e61261a6807043be69

Contents?: true

Size: 926 Bytes

Versions: 5

Compression:

Stored size: 926 Bytes

Contents

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))
        begin
          items_class = table_name.classify.constantize
          items_class.import(items, on_duplicate_key_update: :all)
        rescue NameError => _e # Не обнаружен класс с описанием модели
          keys = items[0].keys.join(",")
          values = items.map { |i| "(#{i.values.map { |v| "'#{v}'" }.join(",")})" }.join(",")
          sql = "insert into #{table_name}(#{keys}) values #{values} on conflict (id) do nothing"
          puts sql
          ActiveRecord::Base.connection.execute sql
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
care-0.1.5 lib/care/seed.rb
care-0.1.4 lib/care/seed.rb
care-0.1.3 lib/care/seed.rb
care-0.1.1 lib/care/seed.rb
care-0.1.0 lib/care/seed.rb