如果我已经为要关联的表创建了模型,如何在 rails 5 中创建外键?

How do I create a foreign key in rails 5 if I've already created the models for the tables I want to associate?

我找到的所有参考资料要么向我展示了如何在 table 创建时执行此操作,要么是针对 rails 的更早版本。理想情况下,我希望 foreign_key 在问题 table 中被命名为 'author_id',以区别于其他可能稍后留下评论或答案的用户。

class Question < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :questions
end

您可以通过 rails generate migration RenameUserFkOnQuestion 在您的终端中创建一个新的空迁移文件。打开它并构建您的迁移。 This is a handy guide 如果您不确定某物的名称。

def change
  change_table :questions do |t|
    t.rename :user_id, :author_id
  end
end

运行 迁移并转到您的模型。您需要像这样更新您的关系:

class Question
  belongs_to :author, class_name: 'User'
end

class User
  has_many :questions, inverse_of: :author
end

那么你应该可以开始了。