Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book