Search code examples
ruby-on-railsrubyactiverecordeventmachinethin

ActiveRecord objects not working in EventMachine callbacks


I ran into the following problem when testing my Rails app.

When making an asynchronous HTTP request with EventMachine I cannot use ActiveRecord objects in the callback for some reason. Whenever I try to access the object I get the following exception:

/home/user/.rvm/gems/ruby-1.8.7-p371/gems/activerecord-2.3.18/lib/active_record/attribute_methods.rb:144:in `create_time_zone_conversion_attribute?': You have a nil object when you didn't expect it! (NoMethodError)
You might have expected an instance of Array.
The error occurred while evaluating nil.include?
from /home/user/.rvm/gems/ruby-1.8.7-p371/gems/activerecord-2.3.18/lib/active_record/attribute_methods.rb:75:in `define_attribute_methods'
from /home/user/.rvm/gems/ruby-1.8.7-p371/gems/activerecord-2.3.18/lib/active_record/attribute_methods.rb:71:in `each'
from /home/user/.rvm/gems/ruby-1.8.7-p371/gems/activerecord-2.3.18/lib/active_record/attribute_methods.rb:71:in `define_attribute_methods'
from /home/user/.rvm/gems/ruby-1.8.7-p371/gems/activerecord-2.3.18/lib/active_record/attribute_methods.rb:257:in `method_missing'

If I remove ActiveRecord objects from the callback, it works ok. Unfortunately I really need them to be accessible, so removing is not an option.

It does not matter if I access the object for reading or writing.

The code I have written looks something like this:

http = EM::HttpRequest.new(url).get(:query => query)

http.callback do
  ....
  object.status = 'delivered'
  object.save!
  ....
end

As for the environment, I have the following setup:

  • Ubuntu 12.04 LTS
  • Ruby 1.8.7-p371
  • Rails 2.3.18
  • Thin server 1.5.0
  • ActiveRecord 2.3.18
  • EventMachine 1.0.0

Does anyone know what might be causing this error? How to fix this?

Thanks in advance!


Solution

  • It seems like all I had to do, was modifying my development configuration file. Setting config.cache_classes = true fixed the problem.