【问题标题】:delayed_job: 'undefined method' error when using handle_asynchronously延迟作业:异步使用句柄时出现“未定义方法”错误
【发布时间】:2021-01-30 19:45:48
【问题描述】:

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

控制器方法

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 启动开发工作进程,然后尝试通过应用程序运行导入。这是我得到的错误:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby csv delayed-job


    【解决方案1】:

    你的导入是一个类方法,你应该在你的模型类名的单例类上调用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
    

    希望这会有所帮助!

    【讨论】:

    • 所以如果我理解正确,我将我的导入方法包装在上面的别名中,在inventory_item.rb?我现在收到NoMethod Error in InventoryItemsController#import 错误,指向在InventoryItem 上调用import 的行。想法?
    • @settheline 我认为您遇到的错误是由于没有删除“自我”。封装在“class
    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多