has_many with multi-level hierarchy and single table inheritance
-
22-09-2019 - |
Question
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?
Solution
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']}