Rails Single Table Inheritance
Ruby on Rails supports Single Table Inheritance. Single Table Inheritance allows you to have one single SQL table, such as an employees table, manage different type of employees like managers and developers. A manager would normally have more responsibilities than a developer and you can separate these additional responsibilities in a different ActiveRecord model class.
Here is another example of Single Table Inheritance that you might find useful. You might have to support a hierarchy of users for you web application, such as User, Editor, and Administrator. An Administrator might have full Create, Read, Update, and Delete (CRUD) access while a User might just have read access. For this hierarchy of users you will need to create a Ruby class for each type and place it in the Rails app/models directory. Here is the base User class:
class User < ActiveRecord::Base end
My Editor class:
class Editor < User end
And the Administrator class:
class Administrator < Editor end
Place each of these classes in their own Rails model file under the app/models directory.
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.
And now, in your controller you can look up all users that are administrators by using the following bit of code:
allAdmins = Administrator.find(:all)
If you want to look up all known users you can do so by using the User class as in the following snippet of code:
allUsers = User.find(:all);
At this point, you would add additional responsibilities to editors and administrators by adding methods to those model classes.