开发者

Inheritance from ActiveRecord Object

Lets say there is a activerecord class called user, which is representative of user table of database.

But I have different type of users which have

  • special functions
  • special variables
  • custom relations (Employer has_many companies, Employee belongs_to company :)

But also these users have a lot of functionality in co开发者_Go百科mmon. So what I want to do is create classes for each different type of user then inherit them from user class.

  • User < ActiveRecord::Base
  • Employer < User
  • Employee < User
  • Customer < User

What is the best way of doing something like that?

Thanks


A lot of applications start out with a User model of some sort. Over time, as different kinds of users emerge, it might make sense to make a greater distinction between them. Admin and Guest classes are introduced, as subclasses of User. Now, the shared behavior can reside in User, and subtype behavior can be pushed down to subclasses. However, all user data can still reside in the users table.

All you need to do is add a type column to the users table that will hold the name of the class to be instantiated for a given row. Active Record takes care of instantiating the kind of object when it loads it from the database.

This technique is called Single Table Inheritance or STI (for short).

A very good recent article about STI is here: http://code.alexreisner.com/articles/single-table-inheritance-in-rails.html


Have a look to this thread on models subclassing:

Subclassing models in Rails

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜