ruby-on-rails - delayed_job : 'undefined method' error when using handle_asynchronously

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

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

Controller 方法

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 时是否遗漏了什么?这个导入过程之前运行良好,所以只是想知道我在哪里搞砸了。提前致谢!

最佳答案

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

希望这对您有所帮助!

关于ruby-on-rails - delayed_job : 'undefined method' error when using handle_asynchronously,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23140914/

相关文章:

ruby-on-rails - 无方法错误 : undefined method `pluck' for #<Model>

ruby-on-rails - 力级加载和卸载 (RoR)

python - 'pandas' 没有属性 'read_csv'"

angularjs - 从 AngularJS 中的智能表导出数据

ruby-on-rails - 为具有 has_many 关系的俄罗斯娃娃缓存构建 Rails 应用程序

mysql - rails : MySQL2 Error when hitting the finder of a model

ruby-on-rails - 如何更改使用 Chartkick 创建的柱形图的颜色?

ruby-on-rails - 文字和构造函数之间的区别? ([] 与 Array.new 和 {} 与 Hash.new)

ruby - 仅当 ruby​​ 中不存在文件时,如何打开文件进行写入

csv - Stata 中的 insheet 和多字符定界符