views:

44

answers:

2

Single Table Inheritance using ActiveRecord. Since we can use @test = Employee.all and find all the employees created. How does rails do this? Since we only use a User Table. How does it know about employees and retrieve only employees? Rails Magic? Explanation anyone? Thank you in advance.

Base Class : Person (inherits ActiveRecord)
Sub-Class: Employee, Supervisor, Manager (each inherit Person)

So my Person table needs to have a _type and _id field to make the table polymorphic.

My next question is how do I get Employee Associated to the Person table and when you save an employee, how do you get it to actually put in Employee in the person_type field?

+1  A: 

To indicate to Ruby on Rails that the users table needs to support Single Table Inheritance you need to add a column named ‘type’ to the users table. Here is my users table definition:

CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, user VARCHAR(15) NOT NULL UNIQUE, pass VARCHAR(40) NOT NULL, type VARCHAR(20) NOT NULL, PRIMARY KEY (id) );

In the column named type you should store the name of the class, the class type, that should be used for each user. To mark an certain user as an admin set his type to ‘Administrator’. By setting a user’s type to ‘Administrator’ you are giving him full administrator privileges as defined in your Administrator model class.

http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/

Matt Briggs
Thanks for the reply, once i have the fields _type and _id, how do I actually get the association placed into that column?
RoR
Oh an actually field named "type" I was thinking of table inheritance with using _type. Thank you.
RoR
+1  A: 

Single table inheritance uses a type column on the table to indicate the type of the object. ActiveRecord knows that your Employee class is using single table inheritance (it has no matching table and the users/people table has a type column).

So when you ask for Employee.all it knows to looks for all entries in the users/people table where type == 'Employee'.

If you look at the logs the SQL will be displayed for these queries and you'll see the 'magic' happening.

Shadwell