fbelanger fbelanger - 2 years ago 69
Ruby Question

Ruby on Rails Resque perform paramters as hash

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]

Which I prefer over
self.perform(arg1, arg2, arg3, arg4, arg5)

Everything works in console (i.e.
). 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
instead of
, since it is serialized?

Answer Source

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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download