How to pass current_user to Sidekiq's Worker

眉间皱痕 提交于 2019-12-07 17:47:38

问题


I am trying to pass current_user or User.find(1) to a worker module but getting error in the sidekiq's dashboard (localhost:3000/sidekiq/retries):

NoMethodError: undefined method `supports' for "#":String

note: my relations are ok ie:

u = User.find(1)
u.supports
#=> []

supports_controller.rb:

def create
 @user = current_user
 ProjectsWorker.perform_async(@user)

 ...

end

app/workers/projects_worker.rb:

class ProjectsWorker
  include Sidekiq::Worker
  def perform(user)
    u = user
    @support = u.supports.build(support_params)
  end
end

Re-starting my sidekiq server makes no difference. This is on my development machine.


回答1:


From the Sidekiq documentation:

The arguments you pass to perform_async must be composed of simple JSON datatypes: string, integer, float, boolean, null, array and hash. The Sidekiq client API uses JSON.dump to send the data to Redis. The Sidekiq server pulls that JSON data from Redis and uses JSON.load to convert the data back into Ruby types to pass to your perform method. Don't pass symbols or complex Ruby objects (like Date or Time!) as those will not survive the dump/load round trip correctly.

Pass an id instead of object:

def create
  ProjectsWorker.perform_async(current_user.id)
end

worker:

class ProjectsWorker
  include Sidekiq::Worker
  def perform(user_id)
    u = User.find(user_id)
    @support = u.supports.build(support_params)
  end
end


来源:https://stackoverflow.com/questions/34380209/how-to-pass-current-user-to-sidekiqs-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!