我找到的所有参考资料要么向我展示了如何在创建表时执行此操作,要么用于更早版本的 rails。理想情况下,我希望在问题表中将 foreign_key 命名为“author_id”,以将其与其他可能稍后留下评论或答案的用户区分开来。
class Question < ApplicationRecord
belongs_to :user
end
class User < ApplicationRecord
has_many :questions
end
我找到的所有参考资料要么向我展示了如何在创建表时执行此操作,要么用于更早版本的 rails。理想情况下,我希望在问题表中将 foreign_key 命名为“author_id”,以将其与其他可能稍后留下评论或答案的用户区分开来。
class Question < ApplicationRecord
belongs_to :user
end
class User < ApplicationRecord
has_many :questions
end
您可以通过在终端中创建一个新的空迁移文件rails generate migration RenameUserFkOnQuestion。打开它并构建您的迁移。如果您不确定某物的名称,这是一个方便的指南。
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
那么你应该很高兴。