Rails 3 - polymorphic associations problem with ActiveRecord::Relation

My application is running over ubuntu 10, ruby 1.9.2, rails 3.0.3 and
passenger 3.0.2 + nginx.

This application has several polymorphic associations and the problem
is that when the associations are called it randomly returns either
the related object or an ActiveRecord::Relation object.

Has anybody had a similar problem or is this a known issue?

Basically the Model looks like this:
class Blahblah < ActiveRecord::Base
  belongs_to :data_object, :polymorphic => true

When I call data_object.id, sometimes I'll get the following error:
"undefined method 'id' for ActiveRecord::Relation"
other times, the association works fine

If I try this in a rails console it seems to always work (could be
because of the inspect the console does).
Basically the issue always occurs when the app is running on nginx or

Any help will be appreciated.

Are you sure that data_object is always a single object and not
sometimes an array (even though containing possibly only one record).
I have seen this when I have used a named scope that I know will
return a single record, but in fact it is an array containing one

Whether you think that may be it or not, if it is a particular line or
a few places in the code that sometimes fails you could catch the
exception there and log the contents of data_object for analysis. Or
if you can make it fail in development use ruby-debug to break into
the exception handler.


After digging a bit deeper we were able to solve this issue.

The details of the fix are explained here


The code examples there apply only to rails 3.0.3, but the idea should
be the same for any other rails 3 release.

Basically the belongs_to association files are using the old finder
methods. these old finder methods seem to return an
ActiveRecord::Relation object at random times.

Our solution was to override the find_target method and change the
finders used for the new Rails 3 format (where(...), etc) through a
couple of initializers.

Hopefully similar corrections will be applied to the next rails