Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Foreign key migration generator for Rails
branch: master

Merge pull request #23 from wizarddevelopment/rake-task

A rake task that checks for missing keys and exits with an error code.
latest commit 4ec007991b
@jenseng authored


Immigrant gives Rails a foreign key migration generator so you can effortlessly find and add missing keys. This is particularly helpful when you decide to add keys to an established Rails app.


Add the following to your Gemfile:

gem 'immigrant'

If you're using a version of Rails prior to 4.2, you'll also need the Foreigner gem.


rails generate immigration AddKeys

This will create a migration named AddKeys which will have add_foreign_key statements for any missing foreign keys. Immigrant infers missing ones by evaluating the associations in your models (e.g. belongs_to, has_many, etc.). Only missing keys will be added; existing ones will never be altered or removed.


If the data in your tables is bad, then the migration will fail to run (obviously). IOW, ensure you don't have orphaned records before you try to add foreign keys.

Known Issues

Immigrant currently only looks for foreign keys in ActiveRecord::Base's database. So if a model is using a different database connection and it has foreign keys, Immigrant will incorrectly include them again in the generated migration.



Copyright (c) 2012-2014 Jon Jensen, released under the MIT license

Something went wrong with that request. Please try again.