如何找到传递给 sidekiq worker 的资源()?



基本上,我有一个代码块需要在sidekiq工作线程中执行,它将通过作为参数传递的资源进行交互(也许(。此资源是 Rails 模型。

与SO上与将参数传递给工人有关的其他问题不同,这里我不知道它是用户模型还是房屋模型。所以我不能简单地使用MyWorker.perform(user_id),因为我不知道我将作为参数传递哪个模型 id。

此外,我读到我不能简单地期望将我的模型对象传递给 sidekiq worker 并在另一端接收它,一旦它将其转换为 json。

所以我想到的是这样的:

# somewhere_in_my_code.rb
MyWorker.perform(resource.id, resource_model) # still don't know what this resource_model would be
# my_worker.rb
def perform(resource_id, resource_model)
model = some_magic_method_to_return_a_model(resource_model)
resource = model.find(resource_id)
# do what I have to do with the resource found
end

但我真的不知道这个some_magic_method_to_return_a_model是否存在。或者如果这可能的话。无论如何,任何帮助将不胜感激,谢谢!

注意:我正在使用Ruby 2.4.8,Rails 4.1.10,Sidekiq 4.1.0

确实如此。假设您有一个User模型:

> user = User.last
> id = user.id
> model_name = user.model_name.name
> model_name.safe_constantize.find(id)
> model_name.safe_constantize.find(id) == user
=> true

这基本上就是多态关联在 Rails 中的工作方式。

最新更新