In Ruby on Rails, how to add foreign key constraint in migration?
Asked
Active
Viewed 8,696 times
4 Answers
14
Here's a gem-based solution that includes support for adding and removing foreign key constraints, doesn't fail with sqlite, and works correctly with schema.rb files:

Jason Wadsworth
- 933
- 1
- 10
- 18
-
FYI, `foreigner` doesn't generate foreign keys in `schema.rb` when using SQLite, because SQLite doesn't support foreign keys. – ashes999 Feb 06 '15 at 23:08
4
This is an update to the matthuhiggins-foreigner gem: http://github.com/sparkfly/foreigner
Features:
- rspec coverage, tested against PostgreSQL 8.3.9 and MySQL 5.0.90
- Migration support
- schema.rb support
Future versions will include CHECK constraints for PostgreSQL, which is needed to implement multi-table inheritance.

Ho-Sheng Hsiao
- 1,327
- 12
- 10
-
Thanks. the foreigner gem does not work well with the change method especially if the table has not been created before. This works great – Sean Feb 08 '12 at 02:06
-
Your welcomed. Let me know (through github) if you find any bugs. – Ho-Sheng Hsiao Feb 08 '12 at 15:38
2
AFAIK, there isn't any built-in support for that, but there are several plugins that help you with that. You can also add them manually to your migration files, just use the execute method for that, e.g. (sample from Rails API):
class MakeJoinUnique < ActiveRecord::Migration
def self.up
execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
end
def self.down
execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
end
end

Adam Spiers
- 17,397
- 5
- 46
- 65

Jeroen Heijmans
- 4,546
- 2
- 17
- 16
-
6Old post, but in case anyone sees this: a unique index is not equivalent to a foreign key constraint, so I believe this code doesn't answer the OP's question. – dsetton Jun 20 '11 at 20:26
0
Would it be enough with adding the following, for example with Products
and User
models?
add_index :products, :user_id

noloman
- 11,411
- 20
- 82
- 129
-
1Adding an index will certainly help with query performance, but it will not make a database enforce foreign key constraints. – Drew Dara-Abrams Aug 03 '12 at 23:25