Method: IshManager::MapsController#import
- Defined in:
- app/controllers/ish_manager/maps_controller.rb
#import ⇒ Object
@TODO: move to models, yes?
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'app/controllers/ish_manager/maps_controller.rb', line 53 def import :create, Map file_data = params[:input] if file_data.respond_to?(:read) contents = file_data.read elsif file_data.respond_to?(:path) contents = File.read(file_data.path) else logger.error "Bad file_data: #{file_data.class.name}: #{file_data.inspect}" end contents = JSON.parse contents contents.deep_symbolize_keys! ## Delete existing if params[:delete_existing] map_ids = contents[:maps].map { |m| m[:_id] } marker_ids = contents[:markers].map { |m| m[:_id] } maps = Map.where( :_id.in => map_ids ) maps.each do |m| marker_ids += m.markers.map(&:_id) end maps.destroy_all Marker.where( :_id.in => marker_ids ).destroy_all end ## ## process content ## errors = [] # profiles profiles = contents[:profiles] contents.delete :profiles profiles.each do |profile| if Ish::UserProfile.where( _id: profile[:_id] ).first errors.push({ message: "profile #{profile[:email]} already exists." }) else p = Profile.new({ email: profile[:email], _id: profile[:_id] }) u = User.where( email: profile[:email] ).first u ||= User.new( email: profile[:email], password: rand.to_s ) flag = u.save && p.save if flag errors.push({ message: "Profile created for #{profile[:email]}." }) else errors.push({ message: u.errors..join(", ") }) errors.push({ message: p.errors..join(", ") }) end end end # everything else contents.each do |k, v| # puts! [k, v], "Importing" item = Map.export_key_to_class[k].constantize v.map do |inn| n = item.new inn begin flag = n.save rescue Mongo::Error::OperationFailure => e errors.push({ class: k, id: inn[:_id], messages: "Mongo::Error::OperationFailure :: |#{e.to_s}|" }) end if flag errors.push({ class: k, id: inn[:_id], messages: 'ok' }) else errors.push({ class: k, id: inn[:_id], messages: "Could not save: |#{n.errors..join(", ")}|." }) end end end flash[:notice] = errors redirect_to action: :index end |