簡體   English   中英

如何在rails中讀取(導入)文件到db使用delay_job

[英]how to read (import) file to db use delay_job in rails

我有一個類導入import_jobs.rb

require 'roo'
class ImportJob < Struct.new(:path, :name)
  def perform
    import(path, name)
  end
  #
  def import(path, name)
    spreadsheet = open_spreadsheet(path, name)
    header = spreadsheet.row(1).map!(&:downcase)

    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose].to_hash     
      potential_user = PotentialUser.find_by_id(row[:id]) || PotentialUser.new
      potential_user.attributes = row
      potential_user.save!
    end
  end
  #
  def open_spreadsheet(path,extname)
    case extname
    when ".csv" then Roo::CSV.new(path)
    when ".xls" then Roo::Excel.new(path)
    when ".xlsx" then Roo::Excelx.new(path,file_warning: :ignore)
    else raise "Unknown file type: extname"
    end
  end
end

在我看來

<%= form_tag import_potential_users_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>

在控制器中

def import
  if params[:file].present?
    Delayed::Job.enqueue ImportJob.new(params[:file].path, File.extname(params[:file].original_filename))
  redirect_to potential_users_path, notice: "Protential Users imported."
  else
    redirect_to potential_users_path
  end
end

在運行作業時,顯示錯誤不退出文件。 當我運行它時,不要使用delay_job,代碼正在工作

[Worker(host:ubuntu pid:14362)] Job ImportJob (id=860) RUNNING
[Worker(host:ubuntu pid:14362)] Job ImportJob (id=860) COMPLETED after 2.0222
[Worker(host:ubuntu pid:14362)] Job ImportJob (id=858) RUNNING
[Worker(host:ubuntu pid:14362)] Job ImportJob (id=858) FAILED (3 prior attempts) with IOError: file /tmp/RackMultipart20151211-14238-13b7xb does not exist
[Worker(host:ubuntu pid:14362)] 2 jobs processed at 0.7092 j/s, 1 failed

看起來臨時文件在工人開始處理作業之前被刪除。 我建議你將文件復制到另一個位置,然后再試一次。 這里有一大堆代碼可能會有所幫助:

if params[:file].present?
  original_filename = params[:file].original_filename
  new_filename = "#{File.basename(original_filename)}_new"
  new_filepath = File.join(Dir.tmpdir, new_filename)
  FileUtils.cp(params[:file].path, new_filepath)
  import_job = ImportJob.new(new_filepath, File.extname(original_filename))
  DelayedJob.enqueue(import_job)
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM