首页 文章

将外键添加到rails模型

提问于
浏览
33

我对铁轨很陌生,并且一直试图在没有运气的情况下整夜工作 .

我创建了3个模型: usersbusinessesbusiness_hours . 我还添加了关联( business_hours belongs_to businesses which belongs_to users )和( user has_one business which has_many business_hours ) .

通过在线阅读文档,我现在需要在我的数据库表中为这些关系创建外键 . 如何使用Rails ActiveRecord迁移执行此操作?我正在使用PostgreSQL作为我的数据库 .

4 回答

  • 6

    首先,当您使用belongs_to方法时,请勿在单词末尾使用 sbusiness_hours belongs_to business which belongs_to user .

    现在创建一个迁移:

    rails generate migration migration_name
    

    在迁移中添加列:

    class MigrationName < ActiveRecord::Migration
      def change
        add_foreign_key :business_hours, :businesses
        add_foreign_key :businesses, :users
      end
    end
    

    运行 rake db:migrate . 而已 .

  • 26

    目前接受的答案并不准确,因为它没有添加数据库外键 . 它只是添加整数列 .

    Rails 4.2.x 中,目前的方法是:

    http://guides.rubyonrails.org/active_record_migrations.html#foreign-keys

    创建迁移:

    rails generate migration migration_name
    

    对于 existing columns ,在迁移中添加如下所示的外键:

    class MigrationName < ActiveRecord::Migration
      def change
        add_foreign_key :business_hours, :businesses
        add_foreign_key :businesses, :users
      end
    end
    

    对于 Rails 4.x 或者如果您要添加 new column 并希望它是外键,您可以执行此操作,您可能还希望将索引指定为true,但这不是外键要求的一部分:

    http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-migration

    class MigrationName < ActiveRecord::Migration
      def change
        add_reference :business_hours, :business, index: true, foreign_key: true
        add_reference :businesses, :user, index: true, foreign_key: true
      end
    end
    
  • 55

    我没有尝试过PostgreSQL,但至少MySQL Rails没有创建外键,我的意思是不是真正的db级外键 . 他们创建的所有内容都是根据约定命名的整数 . 这意味着开箱即用你没有得到这个假外键的索引(为了更快的查找),也没有数据库级别的参照完整性检查 . 为此,您需要执行以下操作:

    ALTER TABLE your_table ADD CONSTRAINT fk_whatever_you_want_to_name_it FOREIGN KEY   (foreign_key_name) REFERENCES another_table(its_primary_key)
    

    在Rails迁移中,您可以将其作为字符串参数传递给“execute”函数 . 添加“真实”外键也会自动创建索引 . 至少对我来说这是一个相当令人讨厌的惊喜 .

  • 3

    Rails 5现在可以在迁移中添加外键,请参阅http://devdocs.io/rails~5.0/activerecord/connectionadapters/schemastatements#method-i-add_foreign_key . 所以

    add_foreign_key :articles, :authors
    

    创建

    ALTER TABLE "articles" ADD CONSTRAINT fk_rails_e74ce85cbc FOREIGN KEY ("author_id") REFERENCES "authors" ("id")
    

    如果您有非标准数据模型,则可以执行此操作 .

    add_foreign_key :articles, :users, column: :author_id, primary_key: "lng_id"
    

    这创造了

    ALTER TABLE "articles" ADD CONSTRAINT fk_rails_58ca3d3a82 FOREIGN KEY ("author_id") REFERENCES "users" ("lng_id")
    

相关问题