Single table inheritance


#1

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


#2

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