Search code examples
rubyruby-on-rails-4rails-activejobsucker-punch

How does a rails asynchronous job let the controller know it's done?


I'm using the newest version of rails and ruby. Through a form I import a CSV which then triggers an async job (I'm using the gem https://github.com/brandonhilkert/sucker_punch for this) that reads the file and handles the data.

All in all everything works fine, however:

My question is, how would I let the controller know when the background job is done? I'd like to redirect with a flash notice but obviously I shouldn't do that from the model... What can I do here?

This is my sucker_punch job:

#app/jobs/import_job.rb

class ImportJob
  include SuckerPunch::Job

  def perform(import_file)
    ActiveRecord::Base.connection_pool.with_connection do
      ModelName.import_from_csv(import_file)
    end
  end
end

And this is my controller action:

def import
  ImportJob.new.async.perform(import_file)
  redirect_to list_data_path, notice: 'Data being imported...'
  # i get sent to list_data_path and i stay there even though the background job already finished successfully
end

Solution

  • For this kind of task I would create a model (ActiveRecord) that holds the status of the job (waiting, processing, done and maybe a progress) and from the controller query the model to present to the use the import job status.