Foreigner
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)
Installation
Add the following to your Gemfile:
“by 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:
“by 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:
“by add_foreign_key(:comments, :posts)
“he :dependent option can be moved from the has_many definition to the foreign key:
“by add_foreign_key(:comments, :posts, dependent: :delete)
“f the column is named article_id instead of post_id, use the :column option:
“by add_foreign_key(:comments, :posts, column: ‘article_id’)
“ name can be specified for the foreign key constraint:
“by add_foreign_key(:comments, :posts, name: ‘comment_article_foreign_key’)
“he :column and :name options create a foreign key with a custom name. In order to remove it you need to specify :name:
“by 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:
“by create_table :products do |t| t.string :name t.integer :factory_id t.foreign_key :factories end
“dd a missing foreign key to comments:
“by change_table :comments do |t| t.foreign_key :posts, dependent: :delete end
“emove an unwanted foreign key:
“by 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:
“by add_foreign_key(:comments, :posts, options: ‘ON UPDATE DEFERRED’)
“
Foreigner Add-ons
- immigrant - generate a migration that includes all missing foreign keys.
- sqlserver-foreigner - A plugin for SQL Server.
License
Copyright (c) 2012 Matthew Higgins, released under the MIT license

