I'm encountering an intermittent error where an ActiveResource resource call like:
Cart.where(session_id: get_guid, status: 1)
Raises an error:
NoMethodError (undefined method `path' for nil:NilClass)
But only intermittently. Restarting the Rails server temporarily solves the problem, but some indeterminate time later, it breaks again.
The source of the issue was due to Rails' autoloading feature. A few realizations led me to this solution.
We had many ActiveResource resources, so in order to easily initialize the resources we placed the setup in an initializer (which is only run during Rails server startup):
# config/initializers/active_resource_setup.rb
Cart.site = ENV["ROOT_URL"]
I also realized that this was not an issue in a production environment. This wasn't as clear before because this issue appeared during a significant Rails upgrade, so I assumed I had broken it to begin with.
However, the source of the issue was Rails automatically reloading the resource class definition files whenever a change was made to the source. It would reload the class definition:
# app/models/resources/cart.rb
class Cart < ActiveResource::Base
validates :session_id, presence: true
end
And because the Cart.site
definition was not in this file as intended, the resource was effectively reset, and the site
configuration clobbered by the auto-reload process.
The solution is to move the Cart.site
definition into the resource definition:
# app/models/resources/cart.rb
class Cart < ActiveResource::Base
self.site = ENV["ROOT_URL"]
validates :session_id, presence: true
end