Support for foreign key constraint in Rails

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


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

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:

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.

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

add_index :products, :user_id

Need Your Help

Using Breeze with RequireJS, Angular is loaded

angularjs requirejs typescript breeze amd

Using TypeScript, AMD, "requirejs", "breeze" but not "angular", I just upgraded from Breeze 1.4.0 to 1.4.6. Now, when "breeze" is loaded, it also tries to load "angular" which fails with...

"Expecting expression" exception thrown when declaring a default element namespace in XQuery

xml namespaces xquery basex

I want to query an XML document containing namespaces, and define a default element namespace. I am using following code in BaseX: