问题
I am using Rails 5.2 for my application and sidekiq for processing the background job.
class Document < ApplicationRecord
has_many :document_jobs
end
class DocumentJob < ApplicationRecord
belongs_to :document
def self.create_document_job(document, status, details)
document.document_jobs.create(status: status, details: details, user_id: user_id)
end
def self.update_document_job(document_job, status, details)
document_job.update(status: status, details: details)
end
end
I want to get the current user in Document job model to store in db.
I am calling create_document_job method in all Sidekiq workers
class DocumentWorker
include Sidekiq::Worker
def perform(*args)
document = Document.find_by_name("sample")
document_job = DocumentJob.create_document_job(document, "processing", "job details")
rescue StandardError => e
DocumentJob.create_document_job(document_job, "failed", "job error details")
end
end
I want to get the current user id when creating the document job in create_document_job method of DocumentJob Model. How can I get it and store it?
回答1:
You can't access the current_user
from Devise in the jobs. So send it as a param from where you call the job.
Also, Sidekiq is using Redis, which only holds key-value pairs. So don't pass along the user object but the user ID and then in the job you can do @user = User.find(user_id)
回答2:
I would recommend passing the user_id as a parameter to the job, because, in the first place, as I see, you only need the user_id, and in the second place it is lighter than passing the full loaded object, which can be inefficient if you storing many job in a queueing DB such as Redis.
If you need to load the user object, you can still do it inside the job by calling:
user = User.find user_id
来源:https://stackoverflow.com/questions/56041019/how-to-get-current-user-in-rails-model