ruby-on-rails - 如何在 ActiveJob 中发送文件?

标签 ruby-on-rails ruby carrierwave

我发送一个大的 .csv 进行处理。文件处理了很长时间,我想把这个任务放在后台。

错误:ActiveJob::SerializationError(不支持的参数类型:文件)

文档说:

Raised when an unsupported argument type is set as a job argument. We currently support NilClass, Integer, Fixnum, Float, String, TrueClass, FalseClass, Bignum, BigDecimal, and objects that can be represented as GlobalIDs (ex: Active Record). Raised if you set the key for a Hash something else than a string or a symbol. Also raised when trying to serialize an object which can't be identified with a Global ID - such as an unpersisted Active Record model.

我想知道有什么办法可以达到这个目的吗?

使用载波

我的服务对象:

class ImportPrice
  attr_accessor :file, :filename

  def initialize(file, filename)
    @file = file
    @filename = filename
  end

  def call
    ImportPriceJob.delay_later(@file, @filename)
  end
end

我的工作:

class ImportPriceJob < ApplicationJob
  queue_as :default

  def perform(file, filename)
    region = Region.find_or_create_by(name: filename)

    Roo::Spreadsheet.open(file).each do |i|
      item = Item.where(oem: i[2]).first

      if item.present?
        item.update_attributes(weight: i[7].to_f)
        # Обновлять только в том случае, если атрибуты изменились
        price = Pricelist.create_with(name: filename).find_or_create_by(region_id: region.id)
        price_item = ItemPrice.create_with(pricelist_id: price.id).find_or_create_by(item_id: item.id)
        price_item.update_attributes(qnt: i[5], cost: i[3].to_i)
      end
    end
  end
end

最佳答案

I want to know is there any way for this purpose?

这样做的目的是序列化过程,这里的@file是一个ruby对象,一个File类的实例,你不能序列化ruby对象(老实说,你可以,但在这种情况下不行),你应该传递一个简单的类型。 不要将整个文件传递给 ImportPriceJob.delay_later(...),只需将路径作为字符串发送。

def call
  path_to_file = @file.path # for example
  ImportPriceJob.delay_later(path_to_file, @filename)
end

然后在延迟作业中打开一个文件,Roo::Spreadsheet.open方法接受文件路径作为参数:

class ImportPriceJob < ApplicationJob
  queue_as :default

  def perform(path_to_file, filename)
    region = Region.find_or_create_by(name: filename)

    Roo::Spreadsheet.open(path_to_file).each do |i|
    # some code here

关于ruby-on-rails - 如何在 ActiveJob 中发送文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48497227/

相关文章:

ruby - "pythonic"的 Ruby 等价物是什么?

ruby-on-rails-3.1 - 使用 CarrierWave 删除文件时清空文件夹

ruby-on-rails - rails +carrierwave 文件上传形式任意文件字段计数

ruby-on-rails - 我可以访问在 ruby​​ on Rails 中调用实例方法的集合吗

ruby-on-rails - ActiveRecord 类方法/关系自

ruby-on-rails - Rails 中的 HTML 实体 link_to

ruby - 为什么我的负载中的数组在 Sinatra/Rack::Test 中被展平了?

ruby-on-rails - Activeadmin - activestorage 删除编辑多张照片

ruby-on-rails - 在 Rails 启动期间创建类的实例

ruby-on-rails - 在 CarrierWave 中,retrieve_from_store 做什么!做?