| Single Table Inheritance Tricks.. |
|
|
|
| Written by Nick Griffith | |
| Tuesday, 30 January 2007 | |
|
Single table inheritance is an extremely powerful and extremely easy thing to do in rails. If you wanted to do this in java you would probably shoot yourself just designing it, but all that pain is relieved inside the wonderful rails framework.
Single table inheritance is an extremely powerful and extremely easy thing to do in rails. If you wanted to do this in java you would probably shoot yourself just designing it, but all that pain is relieved inside the wonderful rails framework.
The ScenarioYou have the need for users to log into your system with different roles and each of these different roles can have different permissions. But these roles also can have things in common and share permissions. You could add a column into the table called 'role' and then do if(role=="admin") to determine what permissions you should do. But there is an easier solution. Single Table Inheritance.
The Table First you would create a table called User and put in your common columns eg. CREATE TABLE `users` (
The ModelThe model that goes along with this table is the User model. Now we want to create an Admin model. Admins have the same characteristics of Users, but have different permissions and abilities. To do this all you have to do is extend the User class instead of the ActiveRecord::Base class.
Tricks with Extending many classesthere are a few things you can do to help this process out. In the previous scenario if i wanted to use the same 'create' page, I would have to determine what class of user I wanted to create before I saved it. This is a helpful method to put in your User class to help.
Another important trick is if you wanted to change that users class or want to know what kind of class he is for display purposes. You would do this by putting these getter and setter methods inside of your User model.
def class_type=(value)
Hope these tips helped. Leave comments if you have any other suggestions or find a flaw with this tutorial. |
|
| Last Updated ( Tuesday, 30 January 2007 ) |
| < Prev |
|---|