Add a reference column migration in Rails 4

前端 未结 7 1823
时光取名叫无心
时光取名叫无心 2020-11-28 00:07

A user has many uploads. I want to add a column to the uploads table that references the user. What should the migration look like?

Here i

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 01:06

    [Using Rails 5]

    Generate migration:

    rails generate migration add_user_reference_to_uploads user:references
    

    This will create the migration file:

    class AddUserReferenceToUploads < ActiveRecord::Migration[5.1]
      def change
        add_reference :uploads, :user, foreign_key: true
      end
    end
    

    Now if you observe the schema file, you will see that the uploads table contains a new field. Something like: t.bigint "user_id" or t.integer "user_id".

    Migrate database:

    rails db:migrate
    

提交回复
热议问题