Search code examples
ruby-on-railsdatabasesidekiq

sidekiq method to store some data in sqlite3 database, rather than redis?


I am currently working on a rails project, i was asked to save progress of a sidekiq workers and store it, so the user who is using the application can see the progress. Now i am faced with this dilemna, is it better to just write out to a text file or save it in a database.

If it is a database, then how to save it in a model object. I know we can store the progress of workers by just sending out the info to log file.

class YourWorker include Sidekiq::Worker

  def perform
  logger.info { "Things are happening." }
  logger.debug { "Here's some info: #{hash.inspect}" }
  end

So if i want to save the progress of workers in a data model, then how?


Solution

  • You can create a Job class and then update some attribute of the currently working job.

    class Job < ActiveRecord::Base
      # assume that there is a 'status' attribute that is defined as 'text'
    end
    

    Then when you queue something to happen you create a new Job and pass the id of the Job to perform or perform_async.

    job = Job.create!
    YourWorker.perform_async job.id
    

    Then in your worker, you'd receive the id of the job to be worked on, and then retrieve and update that record.

    def perform(job_id)
      job = Job.find job_id
      job.status = "It's happening!"
      job.save
    end