Skip to content
Projects

matthuhiggins/foreigner has 1,315 GitHub stars and 122 forks. GitHot measured 0 stars in 24 hours. Last checked 2026-11-07 08:04 UTC. Last push 2019-02-06.

How these counts are measured

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

Measured star growth

in 24h
0
in 7 days
Update delayed
in 15 days
Update delayed
in 1 month
Update delayed

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.md

Original

Foreigner

Build Status Code Climate

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)

Foreigner was rendered obsolete in Rails 4.2. The migration DSL supports foreign keys out of the box via add_foreign_key and remove_foreign_key.

Installation

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, to_table, options)

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

For example, given the following model:

class Comment < ActiveRecord::Base
  belongs_to :post
end

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

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')

The :column and :name options create a foreign key with a custom name. In order to remove it you need to specify :name:

remove_foreign_key(:comments, 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
end

Add a missing foreign key to comments:

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

Remove an unwanted foreign key:

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

Database-specific options

Database-specific options will never be supported by foreigner. You can add them using :options:

add_foreign_key(:comments, :posts, options: 'ON UPDATE DEFERRED')

Foreigner Add-ons

License

Copyright (c) 2012 Matthew Higgins, released under the MIT license

Explore related projects