3

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 common. 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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect thank you. Lastly, what about custom relations for each class?
1

Have a look to this thread on models subclassing:

Subclassing models in Rails

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.