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

Bra*_*kti 17 ruby-on-rails rails-migrations ruby-on-rails-3 ruby-on-rails-4

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

我有一个像这样的模特

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

class PostComment < ActiveRecord::Base
  belongs_to :post, class_name: MyPost
end
Run Code Online (Sandbox Code Playgroud)

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

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 
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*aub 29

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

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
Run Code Online (Sandbox Code Playgroud)

如果要添加唯一约束,则对于index选项也是如此:

t.references :post, foreign_key: { to_table: :my_posts }, index: { unique: true}
Run Code Online (Sandbox Code Playgroud)

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

请参阅实现rails 5.0.rc2rails 4.2中的详细信息

  • [`index`默认为Rails 5中的'true`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference).[`index`在以前的Rails版本中默认为`false`](http://api.rubyonrails.org/v4.2/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference). (5认同)
  • `index`默认为`true`.`index:true`是不必要的. (4认同)

lun*_*unr 14

它应该如下所示:

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 
Run Code Online (Sandbox Code Playgroud)

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

column当列的命名方式不同时,可以使用该选项.