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

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

我有一个像这样的模特

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

现在我想改变我的迁移文件,如下所示:

 class CreatePostComments  MyPost end end 

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

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

 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是引用的别名。

请参阅实施中的详细信息:

rails 5.0.rc2: https : //github.com/rails/rails/blob/v5.0.0.rc2/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb#L68

rails 4.2: https : //github.com/rails/rails/blob/v4.2.6/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb#L312

它应该如下所示:

 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选项。