Skip to content
barunio edited this page Feb 21, 2012 · 3 revisions

Here is a simple example of a polymorpheus migration:

class SetUpPicturesTable < ActiveRecord::Migration
  def self.up
    create_table :pictures do |t|
      t.integer :employee_id
      t.integer :product_id
    end
  
    add_polymorphic_constraints 'pictures',
      { 'employee_id' => 'employees.id',
        'product_id' => 'products.id' }
  end
  
  def self.down
    remove_polymorphic_constraints 'pictures',
      { 'employee_id' => 'employees.id',
        'product_id' => 'products.id' }  
        
    drop_table :pictures
  end
end

The add_polymorphic_constraints has a couple useful options.

Customizing the foreign keys

Suppose that the primary key in your products table is product_code instead of id, and further suppose that this key is a string rather than an integer. You can accomodate that very easily:

create_table :pictures do |t|
  t.integer :employee_id
  t.string  :product_code
end  

add_polymorphic_constraints 'pictures',
  { 'employee_id' => 'employees.id',
    'product_code' => 'products.product_code' }

Setting a uniqueness constraint

Suppose that the picture table has an additional column called url and that we wanted to enforce a uniqueness constraint that no two products or employees can have the same image URL. Polymorpheus can easily set up that uniqueness constraint at the database level with one simple option:

create_table :pictures do |t|
  t.integer :employee_id
  t.integer :product_id
  t.string  :url
end  

add_polymorphic_constraints 'pictures',
  { 'employee_id' => 'employees.id',
    'product_id' => 'products.id' },
  { :unique => 'url' }

The :unique option can also take an array of column names as a value, which creates unique indices that span all of those columns.

Clone this wiki locally