【问题标题】:How do I create a foreign key in rails 5 if I've already created the models for the tables I want to associate?如果我已经为要关联的表创建了模型,如何在 rails 5 中创建外键?
【发布时间】:2017-06-06 02:43:18
【问题描述】:

我找到的所有参考资料要么向我展示了如何在创建表时执行此操作,要么针对的是更早版本的 rails。理想情况下,我希望在问题表中将 foreign_key 命名为“author_id”,以将其与其他可能离开 cmets 或稍后回答的用户区分开来。

class Question < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :questions
end

【问题讨论】:

    标签: foreign-keys rails-activerecord rails-migrations rails-postgresql ruby-on-rails-5.1


    【解决方案1】:

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

    那你应该可以走了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2011-04-21
      • 2021-12-24
      • 1970-01-01
      • 2017-05-20
      • 2021-07-05
      • 2017-04-20
      相关资源
      最近更新 更多