Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_many with multi-level hierarchy and single table inheritance

In my Rails app I have a multi-level hierarchy of the following kind:

class Vehicle < ActiveRecord::Base end
class RoadVehicle < Vehicle end
class Car < RoadVehicle end
class Buss < RoadVehicle end

Then I have a class referencing the middle level like so:

class Garage < ActiveRecord::Base
  has_many :road_vehicles
end

In this simplified example, I have given the vehicles table a type column to enable single table inheritance. Additionally, it contains a garage_id column, to enable the has_many relationship. When I create a new garage and add cars and busses, all get added to the database as expected. However, when I later retrieve the garage object and inspect the road_vehicles collection, it is empty. Can anyone tell me what I'm doing wrong?

like image 733
Pascal Lindelauf Avatar asked Jan 25 '10 22:01

Pascal Lindelauf


1 Answers

When setting up associations with single table inheritance models, you need to refer to the parent model so the associations can infer a table name. So, in your Garage class you need:

has_many :vehicles

If you want to restrict the association to RoadVehicles, you can add conditions:

has_many :vehicles, :conditions => {:type => ['Car', 'Bus']}
like image 125
Alex Reisner Avatar answered Oct 13 '22 13:10

Alex Reisner