set*_*ine 3 ruby csv ruby-on-rails delayed-job
我正在尝试使用delayed_job在我的rails数据库中运行更大的csv导入.这是我的控制器和模型方法:
控制器方法
def import
InventoryItem.import(params[:file], params[:store_id])
redirect_to vendors_dashboard_path, notice: "Inventory Imported."
end
Run Code Online (Sandbox Code Playgroud)
模型方法
def self.import(file, store_id)
CSV.foreach(file.path, headers: true) do |row|
inventory_item = InventoryItem.find_or_initialize_by_upc_and_store_id(row[0], store_id)
inventory_item.update_attributes(:price => row.to_hash["price"], :updated_at => "#{Time.now}")
end
end
handle_asynchronously :import
Run Code Online (Sandbox Code Playgroud)
我已将'delayed_job'和'daemons'添加到我的gemfile中,然后捆绑.运行生成器,启动开发工作进程rake jobs:work,然后尝试通过应用程序运行导入.这是我得到的错误:
Routing Error
undefined method `import' for class `InventoryItem'
Run Code Online (Sandbox Code Playgroud)
在整合delayed_job时我错过了什么吗?这个导入过程之前运行良好,所以只是想知道我搞砸了哪里.提前致谢!
LHH*_*LHH 12
您的import是一个类方法,您应该在模型类名的singleton类上调用handle_asynchronously:
您可以使用元类技巧来替换类方法:
class << self
def import(file, store_id)
CSV.foreach(file.path, headers: true) do |row|
inventory_item = InventoryItem.find_or_initialize_by_upc_and_store_id(row[0], store_id)
inventory_item.update_attributes(:price => row.to_hash["price"], :updated_at => "#{Time.now}")
end
end
handle_asynchronously :import
end
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
2096 次 |
| 最近记录: |