3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# File 'lib/care/seed.rb', line 3
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
|