gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:10 24 4
gpt4 key购买 nike

我发送一个大的 .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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com