问题
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