Has_many with multi-level hierarchy and single table overlay

In my Rails application, I have a multi-level hierarchy of the following form:

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

Then I have a class that references the middle level as follows:

 class Garage < ActiveRecord::Base has_many :road_vehicles end 

In this simplified example, I gave the vehicle table a type column to enable unidirectional inheritance. In addition, it contains a garage_id column to include has_many relationships. When I create a new garage and add cars and buses, they will all be added to the database, as expected. However, when I later get the garage object and check the road_vehicles collection, it is empty. Can someone tell me what I am doing wrong?

+6
ruby-on-rails associations single-table-inheritance
source share
1 answer

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

 has_many :vehicles 

If you want to restrict communication with RoadVehicles , you can add conditions:

 has_many :vehicles, :conditions => {:type => ['Car', 'Bus']} 
+6
source share

All Articles