Support for foreign key constraint in Rails

前端 未结 4 1214
醉话见心
醉话见心 2020-12-28 22:28

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

相关标签:
4条回答
  • 2020-12-28 22:38

    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:

    http://github.com/matthuhiggins/foreigner

    0 讨论(0)
  • 2020-12-28 22:45

    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
    
    0 讨论(0)
  • 2020-12-28 22:47

    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.

    0 讨论(0)
  • 2020-12-28 22:50

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

    add_index :products, :user_id

    0 讨论(0)
提交回复
热议问题