问题描述
我需要在后台标记一组消息(我正在使用 delay_job gem),因为在前台需要一些时间.所以我创建了一个 ActiveJob
类 MarkMessagesAsReadJob
,并将它传递给 user
和 messages
变量以标记所有为 user
读取的 messages
.
I need to mark a collection of messages at the background (I am using delayed_job gem) since it takes some time on the foreground. So I've created an ActiveJob
class MarkMessagesAsReadJob
, and passed it user
and messages
variables in order to mark all of the messages
read for user
.
// passing the values in the controller
@messages = @conversation.messages
MarkMessagesAsReadJob.perform_later(current_user, @messages)
在我的 ActiveJob 类中,我执行任务.
and in my ActiveJob class, I perform the task.
// MarkMessagesAsReadJob.rb
class MarkMessagesAsReadJob < ActiveJob::Base
queue_as :default
def perform(user, messages)
messages.mark_as_read! :all, :for => user
end
end
但是,当我尝试执行任务时,出现错误ActiveJob::SerializationError(不支持的参数类型:ActiveRecord::Associations::CollectionProxy):
However, when I tried to perform the task, I got the errorActiveJob::SerializationError (Unsupported argument type: ActiveRecord::Associations::CollectionProxy):
我读到我们只能将支持的类型传递给 ActiveJob,我认为它无法序列化 CollectionProxy 对象.我该如何解决/解决这个问题?
I read that we can only pass supported types to the ActiveJob, and I think it can not serialize the CollectionProxy object. How can I workaround/fix this?
PS:我考虑过
@messages.map { |message| MarkMessagesAsReadJob.perform_later(current_user, message) }
但是我认为一个一个地标记它们非常昂贵.
however I think marking them one by one is pretty expensive .
推荐答案
我认为最简单的方法是将消息 id 传递给 perform_later()
方法,例如:
I think the easy way is pass message ids to the perform_later()
method, for example:
在控制器中:
@messages = @conversation.messages
message_ids = @messages.pluck(:id)
MarkMessagesAsReadJob.perform_later(current_user, message_ids)
并在 ActiveJob
中使用它:
def perform(user, message_ids)
messages = Message.where(id: ids)
messages.mark_as_read! :all, :for => user
end
这篇关于无法将 CollectionProxy 对象传递给 ActiveJob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!