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

前端 未结 2 2102
半阙折子戏
半阙折子戏 2021-02-18 18:46

How can I assign different table name with adding foreign key. for e.g

I have a model like

class MyPost < ActiveRecord::Base
  has_many :comments, cla         


        
2条回答
  •  悲&欢浪女
    2021-02-18 18:53

    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

提交回复
热议问题