Add a reference column migration in Rails 4

前端 未结 7 1822
时光取名叫无心
时光取名叫无心 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条回答
  •  -上瘾入骨i
    2020-11-28 00:49

    Create a migration file

    rails generate migration add_references_to_uploads user:references
    

    Default foreign key name

    This would create a user_id column in uploads table as a foreign key

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

    user model:

    class User < ApplicationRecord
      has_many :uploads
    end
    

    upload model:

    class Upload < ApplicationRecord
      belongs_to :user
    end
    

    Customize foreign key name:

    add_reference :uploads, :author, references: :user, foreign_key: true
    

    This would create an author_id column in the uploads tables as the foreign key.

    user model:

    class User < ApplicationRecord
      has_many :uploads, foreign_key: 'author_id'
    end
    

    upload model:

    class Upload < ApplicationRecord
      belongs_to :user
    end
    

提交回复
热议问题