0

我发现的所有参考文献都告诉我如何在创建表格时执行此操作,还是为了更早版本的rails。理想情况下,我希望在问题表中将foreign_key命名为'author_id',以便将其与以后可能会留下评论或答案的其他用户区分开来。如果我已经为要关联的表创建了模型,如何在rails 5中创建外键?

class Question < ApplicationRecord 
    belongs_to :user 
end 

class User < ApplicationRecord 
    has_many :questions 
end 

回答

0

您可以通过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 

然后,你应该很好去。

相关问题