2

I'm attempting to have a parent model that other models inherit from, and a secondary class that has associations with the children from the first model. Here's what I have so far...

I used the first command to create the parent model.

rails g model Person name:string age:integer height:float 

I then set up Person as the parent class, and two children class which inherit from it as seen below.

class Person < ActiveRecord::Base
    self.abstract_class = true
end

class Driver < Person
    self.table_name = "Driver"
    belongs_to :vehicle
end

class Passenger < Person
    self.table_name = "Passenger"
    belongs_to :vehicle
end

I also set up a Vehicle class to use in an association with the Driver and Passenger children classes.

rails g model Vehicle color:string capacity:integer

class Vehicle < ActiveRecord::Base
    has_one :driver
    has_many :passengers
end

However, if I use the rails console and attempt to create a new instance Driver or Passenger, using Driver.new or Passenger.new, I encounter an PostgreSQL error.

For reasons which I cannot figure out, Rails is writing SQL statements to query on a Driver or Passenger table. However, it is my understanding that only one Person table is made and has a type attribute that is used for queries.

If anyone can offer some guidance here, I'd be very appreciative.

Thanks

Michael Fich
  • 496
  • 1
  • 7
  • 15

1 Answers1

2

Since it seems you're trying to use the common table persons for both Driver and Passenger, you don't need the abstract_class declaration, or the table_name declarations in either of the sub classes. Per the rails documentation, these options would be used when you want classes to inherit behavior from their parent, without the parent itself having a table.

The snippet below should work fine.

class Person < ActiveRecord::Base
end

class Driver < Person
    belongs_to :vehicle
end

class Passenger < Person
    belongs_to :vehicle
end
Alexa Y
  • 1,854
  • 1
  • 10
  • 13
  • Thank you, Ben! That's definitely helping. I'm still encountering an issue if I attempt to use `Vehicle.driver` to try to add an association though. Any ideas? – Michael Fich Aug 23 '15 at 01:09
  • `$ vehicle = Vehicle.new` and `$ vehicle.driver = Driver.new` lead to the error: `ActiveModel::MissingAttributeError: can't write unknown attribute 'vehicle_id'` – Michael Fich Aug 23 '15 at 01:26
  • I also tried `$ vehicle.driver.build` before the previous commands as well, it produced the error: `NoMethodError: undefined method `build' for nil:NilClass` – Michael Fich Aug 23 '15 at 01:28
  • My best guess is that the `persons` table is lacking a `vehicle_id` column. – Alexa Y Aug 23 '15 at 01:31
  • Oops. Stupid mistake on my part. Thanks for your help! Added `add_column :people, :vehicle, index: true` and it seems to be helping out here. – Michael Fich Aug 23 '15 at 01:37