ActiveRecord provides a single-table inheritance model. Child classes are automatically persisted in the parents table using the “type” column (just a varchar) to figure out which class the data belongs to.
Database schema (MySQL):
CREATE TABLE `topics` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(255) default NULL,
`author_name` varchar(255) default NULL,
`author_email_address` varchar(255) default NULL,
`written_on` datetime default NULL,
`last_read` date default NULL,
`content` text,
`approved` tinyint(1) default 1,
`reply_count` int(11) default NULL,
`parent_id` int(11) default NULL,
`type` varchar(50) default NULL,
PRIMARY KEY (`id`)
);
Model code:
require 'active_record'
class Topic < ActiveRecord::Base
def parent
self.class.find(parent_id)
end
protected
def before_destroy
self.class.delete_all "parent_id = #{id}"
end
end
class Reply < Topic
end
Associations in the above model:
