Crazy @@subclasses magic and ActiveRecord

I’m experiencing this exact behavior using STI

http://www.techlists.org/archives/programming/railslist/2005-12/msg00202.shtml
Here’s a concrete example. Say I have three classes that inherit
from
ActiveRecord, and I have one instance of each in my ‘animals’ table:
Dog < Mammal < Animal < ActiveRecord::Base

Run these command in order and you get:
Mammal.count() = 1
Dog.count() = 1
Mammal.count() = 2!

Here’s the SQL:
SHOW FIELDS FROM animals
SELECT COUNT() FROM animals WHERE ( (animals.type = ‘Mammal’ ) )
SHOW FIELDS FROM animals
SELECT COUNT(
) FROM animals WHERE ( (animals.type = ‘Dog’ ) )
SELECT COUNT(*) FROM animals WHERE ( (animals.type = ‘Mammal’ OR
animals.type = ‘Dog’ ) )

I noticed what’s making this happen is the ActiveRecord::Base
@@subclasses class variable handled by this attribute.
def subclasses
@@subclasses[self] ||= []
@@subclasses[self] + extra =
@@subclasses[self].inject([]) {|list, subclass| list |
subclass.subclasses }
end

Is there a way to “eager load” this variable with @@subclasses[Mammel]
= [Dog] so that whenever I do Mammel.find(:all), I’m also retrieving
records with Dog?

I could switch to polymorphic and it would probably make my
application more scalable, but I’d prefer to stay on one table to
maintain simplicity. This is madness and my head hurts. Anyone have
any suggestions?

Thanks

Kevin

Dude man! Thanks SOOOOO MUCH.
I added require_dependency ‘model’
see the bottom of
http://wiki.rubyonrails.org/rails/pages/SingleTableInheritance

  • DOH! if only I read that more closely.

Are the subclasses in the same file as the base class? If not,
‘require’ or ‘load’ might do the trick.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs