delayed_job: 'undefined method' error when using handle_asynchronously

有些话、适合烂在心里 提交于 2019-12-07 14:21:31

问题


I'm attempting to use delayed_job to run a larger csv import into my rails database. Here are my controller and model methods:

controller method

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

model method

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

I've added 'delayed_job' and 'daemons' to my gemfile, then bundled. Ran the generator, started a development worker process with rake jobs:work, and then tried to run an import through the app. Here's the error I get:

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

Did I miss something when integrating delayed_job? This import process ran fine prior, so just wondering where I've messed up. Thanks in advance!


回答1:


Your import is a class method, you should call handle_asynchronously on your model class name's singleton class:

You can use the metaclass trick to alias class methods:

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

Hope this helps!



来源:https://stackoverflow.com/questions/23140914/delayed-job-undefined-method-error-when-using-handle-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!