如何在不同表名的 Rails 迁移中添加外键 [英] How to add foreign key in rails migration with different table name

查看:48
本文介绍了如何在不同表名的 Rails 迁移中添加外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过添加外键分配不同的表名.例如

How can I assign different table name with adding foreign key. for e.g

我有一个类似的模型

class MyPost < ActiveRecord::Base
  has_many :comments, class_name: PostComment
end

class PostComment < ActiveRecord::Base
  belongs_to :post, class_name: MyPost
end

现在我想像这样更改我的迁移文件:

Now i want to change my migration file like this:

class CreatePostComments < ActiveRecord::Migration
  def change
    create_table :post_comments do |t|
     t.belongs_to :post, index: true
     t.timestamps null: false
    end
    add_foreign_key :post, :class_name => MyPost
  end
end 

但是它不起作用.迁移正在取消.如何更改迁移文件以使用我的模型结构.

But it is not working. Migration is getting cancelled. How do I change my migration file to work with my model structure.

推荐答案

您可以为外键传入选项,如下所示:

You can pass in options for the foreign key as following:

class CreatePostComments < ActiveRecord::Migration
  def change
    create_table :post_comments do |t|
      t.references :post, foreign_key: { to_table: :my_posts }, index: true
      t.timestamps null: false
    end
  end
end

如果您想添加唯一约束,索引选项也是如此:

This is also true for the index option if you like to add a unique constraint:

t.references :post, foreign_key: { to_table: :my_posts }, index: { unique: true}

顺便说一下,references 是 belongs_to 的别名,或者更准确地说,belongs_to 是references 的别名.

By the way, references is an alias for belongs_to, or to be more exact, belongs_to is an alias for references.

详见实现rails 5.0.rc2 &rails 4.2

这篇关于如何在不同表名的 Rails 迁移中添加外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆