How to add foreign key in rails migration with different table name

£可爱£侵袭症+ 提交于 2019-12-04 00:23:01
Stefan Staub

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}

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

See the details in the implementation rails 5.0.rc2 & rails 4.2

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!