Support for foreign key constraint in Rails

In Ruby on Rails, how to add foreign key constraint in migration?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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:

Method 2

This is an update to the matthuhiggins-foreigner gem:


  • 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.

Method 3

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`)"

    def self.down
      execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"

Method 4

Would it be enough with adding the following, for example with Products and User models?

add_index :products, :user_id

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x