# Inheritance Problem

**URL:** <https://www.ruby-forum.com/t/inheritance-problem/177812>\
**Category:** Rails\
**Created:** [October 24, 2009, 12:07pm UTC](https://www.ruby-forum.com/t/inheritance-problem/177812 "2009-10-24T12:07:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![xinu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/f6c823/32.png) [@xinu](https://www.ruby-forum.com/u/xinu)\
**Post date:** [October 24, 2009, 12:07pm UTC](https://www.ruby-forum.com/t/inheritance-problem/177812/1 "2009-10-24T12:07:56Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![xinu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/f6c823/32.png) [@xinu](https://www.ruby-forum.com/u/xinu)\
**Post date:** [October 24, 2009, 12:35pm UTC](https://www.ruby-forum.com/t/inheritance-problem/177812/2 "2009-10-24T12:35:49Z")

</div>

On Oct 24, 11:07 am, “Michael …” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
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
