Inheritance Problem

Hello.

I have a question to inheritance in Rails(2.3.4).

I have this three models.

class Vehicle < ActiveRecord::Base
end

class Car < Vehicle
end

class RallyCar < Car
end

And this Migration:
class CreateVehicles < ActiveRecord::Migration
def self.up
create_table :vehicles do |t|
t.string :name
t.string :brand
t.string :type
t.timestamps
end

Vehicle.create(:name =>'Demo Vehicle', :brand => 'unknown')
Vehicle.create(:name => 'Demo2 Vehicle', :brand => 'unknown')
Car.create(:name => 'My Car', :brand => 'Mercedes')
Car.create(:name => 'My Second Car', :brand => 'VW')
RallyCar.create(:name => 'My Rally Car', :brand => 'Ford')
RallyCar.create(:name => 'My Second Rally Car', :brand => 'Toyota')

end

def self.down
drop_table :vehicles
end
end

This model structur has curious behavior.

Vehicle.count
=> 6

Car.count
=> 2

RallyCar.count
=> 2

Car.count
=> 4

I have the same Problem in find.
Car.find(:all) returns two Records
RallyCar.count
Car.find(:all) returns four Records

Can anyone help me.

Thanks,
Michael

On Oct 24, 11:07 am, “Michael …” [email protected]
wrote:

I have the same Problem in find.
Car.find(:all) returns two Records
RallyCar.count
Car.find(:all) returns four Records

This is a known pecularity of STI - when you do a count for the
subclass it adds a type = “Car” condition. This obviously doesn’t find
instances of RallyCar. Once the RallyCar class is loaded then
ActiveRecord is aware of its existance and will add type = “Car” or
type = “RallyCar” as the condition. It’s a bit messy but in production
it should work fine (since all classes are loaded up front) or you can
also use require_dependency to force them to be loaded (ie at the
bottom of car.rb stick require_dependency ‘rally_car’)

Fred