lib/care/seed.rb in care-0.1.5 vs lib/care/seed.rb in care-0.1.6

- old
+ new

@@ -3,16 +3,18 @@ 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 + 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) - rescue NameError => _e # Не обнаружен класс с описанием модели - keys = items[0].keys.join(",") + else + keys = items[0].keys + v_keys = 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" + 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 \ No newline at end of file