freelancing-god/thinking-sphinx — Issue #310: Subclasses in engines inherit from only partially initialized parents
Author: huerlisi
Created: 2011-11-24 09:51:45+00:00
State: open

I encountered the following problem when accessing an association in a subclass defined in an engine inheriting from an indexed model in the main application:

NoMethodError: undefined method `association_class' for nil:NilClass
from /var/lib/gems/1.8/gems/activerecord-3.1.1/lib/active_record/associations.rb:159:in `association'
from /var/lib/gems/1.8/gems/activerecord-3.1.1/lib/active_record/associations/builder/association.rb:41:in `line_items'
from (irb):1

This happens only in production mode, but not in development mode.

## Problem

After some investigation I could track it down to the following problem:

* indexed class Parent in the application
* Parent.has_many items
* class Child in engine, inheriting from Parent

When the association 'items' is declared after the 'define_index', calls to Child.new.items bail with the above mentioned error.

The problem is that when define_index is called while loading the Parent class, the Parent class has not yet initialized the items association. define_index triggers loading of all models in both the main app and its engines. This includes class Child which inherits from the partially initialized Parent class. While the Parent class later on in its initialization gets the items association properly set up, Child will be left behind.

## Workarounds

I've found three workarounds, all having their problems:

1. Add a "require 'parent'" somewhere in the engine initializer. this triggered a 'const XXX already defined'
2. Specify indexed_models also in production mode. this adds another duplication of information
3. Move define_index below all class method calls in Parent. this is what I'm using now

Big thanks for this nice gem, btw:-)