如何使用不同的表名在rails迁移中添加外键

时间:2015-08-11 08:11:53

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

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

我有一个类似

的模型
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 

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

2 个答案:

答案 0 :(得分:25)

您可以传递外键的选项,如下所示:

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}

顺便说一下,引用是belongs_to的别名,或者更确切地说,belongs_to是引用的别名。

查看实施中的详细信息rails 5.0.rc2&amp; rails 4.2

答案 1 :(得分:12)

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

Take a look at the documentation: http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_foreign_key

You use the column option when the column is named differently.