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

前端 未结 2 2092
半阙折子戏
半阙折子戏 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 19:04

    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.

提交回复
热议问题