Skip to content
This repository


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Adds foreign key helpers to migrations and correctly dumps foreign keys to schema.rb

tree: cda87b4473

Fetching latest commit…


Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 test
Octocat-spinner-32 .gitignore Remove rvmrc from gitignore September 06, 2011
Octocat-spinner-32 .travis.yml
Octocat-spinner-32 Gemfile
Octocat-spinner-32 MIT-LICENSE First! April 15, 2009
Octocat-spinner-32 README.rdoc
Octocat-spinner-32 Rakefile
Octocat-spinner-32 foreigner.gemspec


Foreigner introduces a few methods to your migrations for adding and removing foreign key constraints. It also dumps foreign keys to schema.rb.

The following adapters are supported:

  • mysql2

  • postgres

  • sqlite (foreign key methods are a no-op)


Add the following to your Gemfile:

gem 'foreigner'

API Examples

Foreigner adds two methods to migrations.

  • add_foreign_key(from_table, to_table, options)

  • remove_foreign_key(from_table, options)

(Options are documented in connection_adapters/abstract/schema_definitions.rb):

For example, given the following model:

class Comment < ActiveRecord::Base
  belongs_to :post

class Post < ActiveRecord::Base
  has_many :comments, dependent: :delete_all

You should add a foreign key in your migration:

add_foreign_key(:comments, :posts)

The :dependent option can be moved from the has_many definition to the foreign key:

add_foreign_key(:comments, :posts, dependent: :delete)

If the column is named article_id instead of post_id, use the :column option:

add_foreign_key(:comments, :posts, column: 'article_id')

A name can be specified for the foreign key constraint:

add_foreign_key(:comments, :posts, name: 'comment_article_foreign_key')

Change Table Methods

Foreigner adds extra methods to create_table and change_table.

Create a new table with a foreign key:

create_table :products do |t|
  t.string :name
  t.integer :factory_id
  t.foreign_key :factories

Add a missing foreign key to comments:

change_table :comments do |t|
  t.foreign_key :posts, dependent: :delete

Remove an unwanted foreign key:

change_table :comments do |t|
  t.remove_foreign_key :users

Foreigner Add-ons


Copyright © 2012 Matthew Higgins, released under the MIT license

Something went wrong with that request. Please try again.