在 Rails 5 中添加引用列迁移 [英] Add a reference column migration in Rails 5
问题描述
一个用户有很多上传.我想在引用用户的上传表中添加一列.迁移应该是什么样的?
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?
Rails 3 的相关问题:Rails 3 迁移:添加引用列?
Related question for Rails 3: Rails 3 migrations: Adding reference column?
Rails 4 的相关问题:在 Rails 4 中添加引用列迁移
Related question for Rails 4: Add a reference column migration in Rails 4
Rails 6 的相关问题:How使用 SQLite 在 Rails 6 中添加引用列迁移
Related question for Rails 6: How to add reference column migration in Rails 6 with SQLite
推荐答案
与之前版本的 Rails 一样,您可以使用以下命令来创建迁移:
As with prior versions of Rails, you may use the following command to create the migration:
rails g 迁移 AddUserToUploads user:references
与以前版本的 Rails 不同,迁移看起来像:
Unlike prior versions of Rails, the migration looks like:
class AddUserToUploads < ActiveRecord::Migration[5.0]
def change
add_reference :uploads, :user, foreign_key: true
end
end
这篇关于在 Rails 5 中添加引用列迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!