Complex Classes

For Photo Share, we’ve built an object model in which one table relates to one class. Sometimes you’ll want to map more sophisticated object models to a database table. The two most common scenarios for doing so are inheritance and composition. Let’s look at how you’d handle each mapping with Active Record. These examples are not part of our Photo Share application, but the problems are common enough that we will show them to you here.

Inheritance

Active Record supports inheritance relationships using a strategy called single-table inheritance, shown in Figure 3-1. With this kind of inheritance mapping, all descendants of a common class use the same table. For example, a photographer is a person with a camera. With single-table inheritance, all columns for both Person and Photographer go into the same table. Consider the table created by this migration:

$ script/generate model person
      exists  app/models/
      exists  test/unit/
      exists  test/fixtures/
      create  app/models/person.rb
      create  test/unit/person_test.rb
      create  test/fixtures/people.yml
      exists  db/migrate
      create  db/migrate/20080510174956_create_people.rb

As usual, you can edit the migration in db/migrate/20080510174956_create_people.rb:

class CreatePeople < ActiveRecord::Migration
  def self.up
    create_table :people do |t|
      t.string :name, :type, :email, :camera
      t.timestamps
    end
  end

  def self.down
    drop_table :people
  end
end

Next, run the migration:

rake db:migrate (in /Users/lancelotcarlson/Projects/book/repo/current/src/chapter3/photos) ...

Get Rails: Up and Running, 2nd Edition 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.