【问题标题】:Is there a way to change column to foreign key?有没有办法将列更改为外键?
【发布时间】:2019-06-05 05:08:07
【问题描述】:

我在名为 contents 的表中有一个现有的列 project_id。它应该是一个引用项目表中项目的 foreign_key。但是,无论谁设置了数据库,都没有将 project_id 设置为 foreign_key,而是创建了目录表。

我尝试将迁移创建为:

def change
    add_reference :contents, :project
end

但这会尝试添加一个已经存在的列project_id

我的问题是,有没有办法(使用迁移)将列 project_id 更改为 foreign_key?

【问题讨论】:

    标签: ruby-on-rails rails-migrations


    【解决方案1】:

    Rails 5+ 允许您添加 foreign_key constraints using migration

    add_foreign_key :contents, :projects, column: :project_id, #primary_key: "id"
    

    除此之外,您不需要 ActiveRecord 的外键约束来正确映射迁移中的关系,即 foreign_key 约束也可以在模型级别显式设置。使用迁移在project_id 上更快地检索add indexing

    例子-

    class Content < ApplicationRecord
      belongs_to :project, class_name: 'Project', :foreign_key => "project_id"
    end
    
    class Project < ApplicationRecord
     has_many :contents, class_name: 'Content', :foreign_key => "project_id",  :dependent => :destroy
    end
    

    【讨论】:

    • 我在寻找方法 1。我知道方法 2(通过模型)。谢谢。
    【解决方案2】:

    你可以试试

    add_foreign_key :contents, :projects, column: :project_id
    

    更多详情可以参考here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多