Tuesday, January 30, 2007

Single Table Infuriation

Single Table Inheritance in Rails is an excellent pattern that works really well, except when it doesn't.


class Parent < ActiveRecord::Base
end

class Child < Parent
end

class GrandChild < Child
end


Each of the above classes are defined in their own files (app/models). There are times in development mode that I've noticed that Child.find(:all) will generate the following SQL:


SELECT * FROM parents WHERE (type='Child')


In Rails 1.2 the fix for this is perhaps a little obfuscated.


class Parent < ActiveRecord::Base
require_dependency 'child'
end

class Child < Parent
require_dependency 'grand_child'
end

class GrandChild < Child
end


Now, the other part of this solution is that you probably want to call require_dependency at the end of the class definition as there may be methods in the parent object that the child object needs. I suppose you could re-open the class at the end of the file.

1 comment:

brink said...

Interestingly, A-dog at work sent me this link

http://sean-carley.blogspot.com/2006/05/when-rails-needs-clue-single-table.html

Funny how that's almost a year ago and seems to describe the same problem you mention.