如何在 Rails 模型中获取当前用户 [英] How to get current user in Rails model
问题描述
我的应用程序使用 Rails 5.2,使用 sidekiq 处理后台作业.
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.
我在所有 Sidekiq 工人中调用 create_document_job 方法
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
我想在 DocumentJob 模型的 create_document_job 方法中创建文档作业时获取当前用户 ID.我如何获取和存储它?
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?
推荐答案
您无法在作业中从 Devise 访问 current_user
.因此,将其作为参数从您调用作业的位置发送.此外,Sidekiq 使用 Redis,它只保存键值对.所以不要传递用户对象而是用户 ID,然后在工作中你可以做 @user = User.find(user_id)
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)
这篇关于如何在 Rails 模型中获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!