Forum: Ruby on Rails single table inheritance

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Luma (Guest)
on 2008-12-26 12:59
(Received via mailing list)
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
Frederick C. (Guest)
on 2008-12-26 13:11
(Received via mailing list)
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
This topic is locked and can not be replied to.