I'm trying to write a resque worker to handle some background tasks like mass emailing.
What I'd like is for my worker to accept a hash of arguments:
class Worker
@queue = :worker_queue
def self.perform(options={})
user_id = options[:user_id]
end
end
Which I prefer over self.perform(arg1, arg2, arg3, arg4, arg5)
.
Everything works in console (ie Worker.perform(args)
). However, whenever I queue this into resque the arguments are undefined.
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=
Can anyone point me in the right direction? I know that the enqueued paramters are serialized into JSON.
I just thought about it and could my problem be the symbol :user_id
instead of 'user_id'
, since it is serialized?
Yes, it's correct. The following code is the culprit
user_id = options[:user_id]
Specifically, the use of a symbol in the hash ( :user_id
) can cause the trouble because when the parameters are serialized/deserialized, the Hash you get in the Resque worker contains all the keys as strings.
You should use:
user_id = options["user_id"]
Yes my suspicions were correct! When serialized to JSON, a Ruby symbol becomes a regular key string.
As soon as I replaced the previous code's symbols with 'user_id'
, everything started working!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.