通过 sidekiq 导入 csv 的未定义方法“路径”
undefined method `path' with csv import via sidekiq
我正在尝试通过 sidekiq
导入大型 csv。但是我遇到了问题。
我在我的控制器中写了 import
方法。
def import
Importcsv.perform_async(params[:file])
redirect_to calendars_path, notice: "Calendar imported."
end
工人代码在这里。
class Importcsv
include Sidekiq::Worker
sidekiq_options queue: "high"
def perform(file)
CSV.foreach(file.path, headers: true) do |row|
calendar = find_by_id(row['id']) || new
calendar.attributes = row.to_hash
calendar.save
end
end
end
但是我得到这个错误 undefined method
path' for "/tmp/RackMultipart20150928-8812-sgwsm5":String`
您的错误日志表明,您正在尝试从 String
的实例中获取 path
。你可以试试这个代码:
def perform(file)
file = file.path if file.is_a?(File)
CSV.foreach(file, headers: true) do |row|
# ...
end
end
这样您就可以在该方法中同时接受 String
和 File
参数。另请注意,在使用 Sidekiq 时,您不能将 File
作为参数传递。阅读更多详细信息 here。
我通过传递单行解决了这个问题,例如
CSV.foreach(params[:file].path, headers: true) do |row|
attrs ={name: row[0]}
Importcsv.perform_async(attrs)
end
我正在尝试通过 sidekiq
导入大型 csv。但是我遇到了问题。
我在我的控制器中写了 import
方法。
def import
Importcsv.perform_async(params[:file])
redirect_to calendars_path, notice: "Calendar imported."
end
工人代码在这里。
class Importcsv
include Sidekiq::Worker
sidekiq_options queue: "high"
def perform(file)
CSV.foreach(file.path, headers: true) do |row|
calendar = find_by_id(row['id']) || new
calendar.attributes = row.to_hash
calendar.save
end
end
end
但是我得到这个错误 undefined method
path' for "/tmp/RackMultipart20150928-8812-sgwsm5":String`
您的错误日志表明,您正在尝试从 String
的实例中获取 path
。你可以试试这个代码:
def perform(file)
file = file.path if file.is_a?(File)
CSV.foreach(file, headers: true) do |row|
# ...
end
end
这样您就可以在该方法中同时接受 String
和 File
参数。另请注意,在使用 Sidekiq 时,您不能将 File
作为参数传递。阅读更多详细信息 here。
我通过传递单行解决了这个问题,例如
CSV.foreach(params[:file].path, headers: true) do |row|
attrs ={name: row[0]}
Importcsv.perform_async(attrs)
end