Single Table Inheiritence (in Rails) for the impatient

Posted by kev Wed, 24 Aug 2005 07:10:00 GMT

  • Create a column to hold the object type (automagically works for ‘type’) in the table corresponding to the model you want to inheirit from.
  • Create a model, and set it to inherit like so:

Class BaseClass < ActiveRecord::Base

Class ChildClass < BaseClass

  • Profit!

No, but seriously, you can now use to create a new ChildClass. It will use the same table as BaseClass. If you want the child class to have more attributes than its parent, add more columns and simply ignore them for the parent. For a full rationale behind why just ignoring them is ok, buy the Agile Rails book. It boils down to convenience and utility. We can easily do this. If you want to impose restrictions on your own to stop base classes or children of a common base class from accessing each others attributes, you’re welcome to add it to the model code.

For more information, including how to set the column to be something other than type, see the api documentation.

Posted in , ,  | no comments | no trackbacks



Use the following link to trackback from your own site:

Comments are disabled