Sexy PG Constraints now supports foreign key and mutlicolumn constraints

The title sums it up pretty much. Now you can do things like following.

class AddConstraintsToBooks < ActiveRecord::Migration
  def self.up
    constrain :books do |t|
      t[:title, :author_id].all :unique => true # Notice how multiple columns are listed in brackets.
    end
  end

  def self.down
    deconstrain :books do |t|
      t[:title, :author_id].all :unique
    end
  end
end

And here’s the foreign key example.

class AddConstraintsToBooks < ActiveRecord::Migration
  def self.up
    constrain :books do |t|
      t.author_id :reference => {:authors => :id, :on_delete => :cascade} # :on_delete is optional
    end
  end

  def self.down
    deconstrain :books do |t|
      t.author_id :reference
    end
  end
end

Leave a Reply