vendredi 21 août 2015

Rails NameError for Models when using multiple threads

I'm having trouble with resolving what seems like a thread issue with ActiveRecord in Rails. Here's the situation:

In the backend, I have a class method "make_db_call" that uses ActiveRecord to make a call to a database table named "User". This database call can take a while, so I decided to use threads that calls this method. However, sometimes, I get a NameError on the model User. Here's the code:

class MyClass
    def self.make_db_call()
        result = User.query_db_via_active_record   # Where the ERROR occurs!
        return result
    end
end

In some other file...

...
threads = []
threads << Thread.new { MyClass.make_db_call }
threads << Thread.new { MyClass.make_db_call }
threads.each do |t|
    t.join
end
...

The error occurs when at the line:

result = User.query_db_via_active_record

This is the error:

NameError (uninitialized constant MyClass::User):

NOTE: Sometimes, I get no error. But most of the time, I get the error. This makes it seem like this is some threading issue.

Has anyone seen this problem?
What could be the cause of the problem?
How can I solve the problem?

Aucun commentaire:

Enregistrer un commentaire