delayed_job:使用handle_asynchronously时出现’undefined method’错误

我正在尝试使用delayed_job在我的rails数据库中运行更大的csv导入。 这是我的控制器和模型方法:

控制器方法

def import InventoryItem.import(params[:file], params[:store_id]) redirect_to vendors_dashboard_path, notice: "Inventory Imported." end 

模型方法

 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 

我已将’delayed_job’和’daemons’添加到我的gemfile中,然后捆绑。 运行生成器,使用rake jobs:work启动开发工作进程rake jobs:work ,然后尝试通过应用程序运行导入。 这是我得到的错误:

 Routing Error undefined method `import' for class `InventoryItem' 

在整合delayed_job时我错过了什么吗? 这个导入过程之前运行得很好,所以只是想知道我搞砸了哪里。 提前致谢!

您的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 

希望这可以帮助!