7.7. Advanced ActiveRecord

Having covered most of what makes ActiveRecord an excellent ORM, you can move onto the next level, with more advanced topics; the knowledge of which will certainly come in handy more than a few times.

7.7.1. Single Table Inheritance

Relational databases work under the assumption that tables can be related through associations, as you have seen so far in this chapter. Object-oriented programming tends to use, where appropriate, inheritance, a concept that is foreign to the world of RDBMS. To bridge this gap, ActiveRecord allows you to easily implement single table inheritance.

Imagine that you want to represent photos, videos, and songs in your application. The traditional approach would be to use three tables (and three corresponding models):

create_table :songs do |t|
  t.string :name
  t.string :file_path
  t.integer :user_id
end
create_table :videos do |t|
  t.string :name
  t.string :file_path
  t.integer :user_id
end

create_table :photos do |t|
  t.string :name
  t.string :file_path
  t.integer :user_id
end

The problem with this approach is that it forces you to use three structurally identical tables to represent what are essentially just media files. Single table inheritance allows you to use a single common table for all three of them, whose corresponding model is the superclass of the three (Song, Video, and Photo) models.

The single table will be media_files:

create_table :media_files do |t| t.string :name t.string :file_path t.string :type t.integer :user_id ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.