2017-12-28 52 views
0

CSV 업로드를 통해 일부 목록을 가져오고 싶은 프로젝트에서 작업하고 있습니다. 레일 앱을 사용하면 프런트 엔드에서 CRUD 작업을 수행 할 수 있습니다.레일스 : CSV 일괄 업로드를 위해 업 로더를 우회하는 방법

class Listing < ActiveRecord::Base 
    mount_uploader :image, ImageUploader 
end 

업 로더 클래스는 다음과 같다 :

# encoding: utf-8 

class ImageUploader < CarrierWave::Uploader::Base 


    include CarrierWave::MiniMagick 
    storage :fog 

    def store_dir 
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 
    end 


    #Create different versions of your uploaded files: 
    version :thumb do 
    process :resize_to_fit => [200, 200] 
    end 

end 

하지만 백엔드에

, 나는 때 이미지를 안개 이미지 업로드를 우회하려고 다음과 같이

목록 클래스입니다 URL은 이미 CSV 파일에서 제공됩니다. 이미지 업 로더를 실행하고 싶지 않습니다.

저는 CSV 업로드 작업을하고 있습니다. 나는 그것이 데이터의 해시와 목록을 저장할 때 nil을 나에게주고 URL로 이미지를 설정하려고 할 때

def self.import(file)  
     count = 0 
     CSV.foreach(file, headers: true, encoding:'iso-8859-1:utf-8') do |row| 


      data = {} 

      row.to_hash.each do |k, v| 
       key = MAP[k] 
       data[key] = v 
      end 

      unless data[:vin] == nil 


       listing = Listing.find_by_vin(data[:vin]) || Listing.new 

       #listing.attributes = (row.to_hash).merge(image: URI.parse(row['image'])) #   
       listing.title = "#{data[:year]} #{data[:make]} #{data[:model]}" 


       unless data[:all_images] == nil 



        listing_images = data[:all_images].split(",") 
        i = 0 

        [:image, :imagefront, :imageback, :imageleft, :imageright, :frontinterior, :rearinterior].each do |image|    
         unless listing_images.size < 1 
          data[image] = listing_images[i]       
          i += 1 
         end 
         p "hello" 
        end 

       end 


       data.delete(:all_images) 


       p data 
       listing.attributes = data 


       if listing.valid?     
        if listing.save! 
         count = count+1 
        end         
       end 


      end 
     end 

     return count 
    end 

:처럼 현재, 코드가 보인다. 그러나 함수에 사용 된 해시 데이터에는 테스트 및 나열의 결과로 아래 보이는 image 속성이 있습니다. image 속성도 있습니다. enter image description here

내 주요 질문은 : 가 어떻게 생성 목록에서 업 로더 조치를 무시하고 csv 파일에 주어진 URL 문자열에 이미지 URL을 설정/우회 할 수있다. URL을 설정하더라도 설정되지 않고 목록이 다음과 같이 저장됩니다. image as nil.

답변

0

문제가 직접 해결되었습니다. 비슷한 문제에 직면 할 수있는 사람들을위한 답.

주어진 URL에서 이미지를 가져 오는 데 open-uri를 사용한 다음 결과를 루프의 목록 속성 이미지에 할당했습니다.

[:image, :imagefront, :imageback, :imageleft, :imageright, :frontinterior, :rearinterior].each do |image|    
    unless listing_images.size < 1 
    data[image] = CsvUploading::picture_from_url(listing_images[i]) 
    i += 1 
    end    
end 

모듈의 picture_from_url 함수를 분리하여 다른 클래스에서 다시 사용할 수 있습니다.

require "open-uri" 

module CsvUploading 

    def self.picture_from_url(url) 
    open(url) 
    end 
end 

P. 이 영웅에 대해서도 마찬가지입니다. 이제 문제는 CSV 업로드가 많은 쿼리를 수행하고 있으며 영웅이 애플리케이션 오류를 발생시키고 있다는 것입니다. 대신 배치 쿼리를 사용해야합니다.