# Single table inheritance

**URL:** <https://www.ruby-forum.com/t/single-table-inheritance/156389>\
**Category:** Rails\
**Created:** [December 26, 2008, 11:59am UTC](https://www.ruby-forum.com/t/single-table-inheritance/156389 "2008-12-26T11:59:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![luma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/d6d6ee/32.png) [@luma](https://www.ruby-forum.com/u/luma)\
**Post date:** [December 26, 2008, 11:59am UTC](https://www.ruby-forum.com/t/single-table-inheritance/156389/1 "2008-12-26T11:59:53Z")

</div>

hi,

I have the models:

order\_item.rb:  
class OrderItem \< ActiveRecord::Base  
end

foreign\_item.rb:  
class ForeignItem \< OrderItem  
has\_many :purchased\_items  
end

retailler1\_item.rb  
class Retailer1Item \< ForeignItem  
end

retailler2\_item.rb  
class Retailer2Item \< ForeignItem  
end

purchased\_item.rb:  
class PurchasedItem \< ActiveRecord::Base  
belongs\_to :foreign\_item  
end

Now I have an instance of PurchasedItem and would like to get its  
foreign\_item:

foreign\_item = purchased\_item.foreign\_item  
(purchased\_item.foreign\_item\_id == 100, and the related foreign\_item  
has type == ‘Retailer1Item’ or type == ‘Retailer2Item’)

The sql-query should look like:  
“SELECT FROM order\_items WHERE order\_items.id = 100 AND  
(order\_items.type = ‘ForeignItem’ OR order\_items.type =  
‘Retailer1Item’ OR order\_items.type = ‘Retailer2Item’)”

but this is executed:

[4;36;1mForeignItem Columns (0.007000) [0m [0;1mSHOW FIELDS FROM  
`order_items` [0m  
[4;35;1mForeignItem Load (0.001000) [0m [0mSELECT \* FROM  
`order_items` WHERE (`order_items`.`id` = 100) AND  
( (`order_items`.`type` = ‘ForeignItem’ ) ) [0m

Thus, the foreign\_item cannot be found. The same when I explicitly use  
ForeignItem.find

What can I do?

Luma

---

<div class="post-metadata">

**Author:** ![luma](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/d6d6ee/32.png) [@luma](https://www.ruby-forum.com/u/luma)\
**Post date:** [December 26, 2008, 12:11pm UTC](https://www.ruby-forum.com/t/single-table-inheritance/156389/2 "2008-12-26T12:11:01Z")

</div>

On 26 Dec 2008, at 10:59, Luma wrote:

> "SELECT FROM order\_items WHERE order\_items.id = 100 AND
> 
> Thus, the foreign\_item cannot be found. The same when I explicitly use  
> ForeignItem.find

This is STI magic. At this point the classes Retailer1Item and  
Retailer2Item item have not been loaded and Active Record is not aware  
of their existence. if you require them explicitly with  
require\_dependency (eg at the bottom of foreign\_item.rb) then it  
should do the right thing.

Fred
