【问题标题】:How to add foreign key in rails migration with different table name如何在具有不同表名的 Rails 迁移中添加外键
【发布时间】:2015-08-11 08:11:52
【问题描述】:

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

我有一个类似的模型

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

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

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

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 

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

【问题讨论】:

  • t.belongs_to :post, index: true 为您创建了外键。为什么你又在尝试?我没有得到你想要做的事情..
  • 您的迁移产生的错误是什么?

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 rails-migrations


【解决方案1】:

您可以按如下方式传入外键选项:

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

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

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

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

详见实现rails 5.0.rc2 & rails 4.2

【讨论】:

【解决方案2】:

应该是这样的:

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_comments, :my_posts, column: :post_id
  end
end 

查看文档:http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_foreign_key

当列名称不同时,您使用column 选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-24
    • 2015-03-04
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2015-03-03
    • 2019-11-05
    相关资源
    最近更新 更多