Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Table Inheritance in Rails 3

I'm currently working on a Rails 3 application that looks like it might need to use Class Table Inheritance for a couple of models.

A simplified example of what's going on is this.

I have a class called Person with general attributes like name, email, password which are common to all types of people in the application and used for authentication.

There are two subclasses to Person (or two types of people...), Driver and Passenger. Both of these subclasses share the generic attributes of Person but then have specific additional attributes which are unique to themselves. (for example a Driver can have many Vehicles and Licenses but a Passenger would not)

How would I implement CTI for this kind of situation? I've been looking at an example provided here:

http://rhnh.net/2010/08/15/class-table-inheritance-and-eager-loading

But it doesn't speculate on how to access the common attributes of a Person from a Driver or Passenger object and I'm a bit confused by that.

In particular, what I'd like to know is:

If I'm updating the attributes of a Driver, how can I easily access and update the relevant attributes on the parent people table? Do I have to hook into an after_save callback and separate out which attribute update goes where? Or is there a better way to approach this?

like image 941
Ganesh Shankar Avatar asked Aug 17 '10 03:08

Ganesh Shankar


3 Answers

Also there is a plugin 'acts_as_relation' to do this,
https://github.com/hzamani/acts_as_relation/

in your case the code will be this:

class Driver < ActiveRecord::Base
   acts_as :person
end

class Passenger < ActiveRecord::Base
  acts_as :person
end

Don't forget to add person_type and person_id columns to persons table.
Now both Drive and Passenger inherit Person attributes, validations and methods.

like image 89
Hassan Avatar answered Sep 19 '22 13:09

Hassan


why not using Single Table Inheritance? for example:

class Person < ActiveRecord::Base
   # some common code here
end

class Driver < Person
   # Driver code
end

class Passenger < Person
   # Passenger code
end

in this way you'll have a common class Person, plus two specific classes derived from it

like image 24
Andrea Pavoni Avatar answered Sep 18 '22 13:09

Andrea Pavoni


I'm using the class table inheritance plugin and it working well, http://github.com/brunofrank/class-table-inheritance

like image 22
Bruno The Frank Avatar answered Sep 21 '22 13:09

Bruno The Frank