Tuesday, February 16, 2010

Multi-level Single Table Inheritance (STI) in Rails

This took me more than one attempt to get right, so I thought I'd blat it out in a blog post in case anyone else has been struggling with it. In the end, the implementation matches your intuition, but getting the sub-classing syntax right took a few tries (undoubtedly due to my relative newness to Rails/Ruby).

Why would you want multi-level STI? When you're using multiple inheritance (class_c inherits from class_b and class_b inherits from class_a) and you want that relationship maintained through ActiveRecord; that's when.

Take the following three classes for example:

class A
def method_a

/app/model/a/class_b.rb (yes, I mean dir 'a'. class_b.rb is a peer of class_a.rb)
class A::B < A
def method_b

class A::B::C < A::B
def method_c

Notice the explicit class hierarchy notation. Without this, I can't get the multi-level relationship maintained through STI.

From here, you can merrily create the class through ActiveRecord, assuming you have an existing table for the base class (which includes the 'type' column (where AR stashes the class hierarchy/name information for subsequent instanciations), and use all the methods.

c = A.first
c.method_a => 'a'
c.method_b => 'b'
c.method_c => 'c'


Anonymous said...

great site www.blogger.com. Offtopic: Will there be a new part of "Harry Potter?"
a dogs penis [url=http://viagravillage.com/#nrtqhhf]generic viagra price canada[/url] drug quotes

Anonymous said...

[url=http://buyviagrapremiumpharmacy.com/#nonlh]buy cheap viagra[/url] - buy viagra online , http://buyviagrapremiumpharmacy.com/#iusxw viagra online

Anonymous said...

This latest jackpot win in fact the inside information roughly a bonus ahead you determine to have it. [url=http://www.onlinecasinoburger.co.uk/]online casino games[/url] online casinos uk Click what can be used with this lineament in judgement. http://www.tasty-onlinecasino.co.uk/

Anonymous said...

After all it does not take underwriter with an IPO which decides who gets Initial public offering shares and the way many, in fact it is not an possibly distribution UK Business Angels Association The amount that this agency is able to mortgage you for faculty depends drastically on where you're applying for a person's college bank loan