【问题标题】:Rails5 migration : Table has no foreign key forRails5迁移:表没有外键
【发布时间】:2018-08-24 00:11:31
【问题描述】:

将我的 Rails 4.2 应用程序迁移到 Rails 5 后,当我尝试从新数据库迁移时,出现以下错误

表“目标”没有 development_plan 的外键

以下是重要的迁移:

  1. 使用 add_reference 创建外键

    class AddDevelopmentPlanToObjectives < ActiveRecord::Migration
      def change
        add_reference :objectives, :development_plan, index: true, foreign_key: true
      end
    end
    
  2. 删除外键(产生错误)

    class DropDevelopmentPlans < ActiveRecord::Migration
      def change
        Objective.all.each do |objective|
          company = objective.owner.company
          company.cycles.create name: '4Q 2015', begin_at: Date.today, end_at: 1.year.from_now, current: true unless company.current_cycle
          company.reload
          objective.update cycle: company.current_cycle
        end
        remove_foreign_key :objectives, :development_plan
        remove_reference :objectives, :development_plan, index: true
        drop_table :development_plans
      end
    end
    

remove_foreign_key :objectives, :development_plan 上的迁移中断

有人遇到过这个问题吗?这也发生在其他类似的迁移中......

【问题讨论】:

  • 所以你的迁移添加了外键,然后一个后期删除它?
  • 没关系,我刚刚意识到第一个是Add,第二个是Drop

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

我认为 to_table 应该以复数形式倾斜:

remove_foreign_key :objectives, to_table: :development_plans

请参考rails api docs

【讨论】:

    【解决方案2】:

    参考这篇文章:https://blog.bigbinary.com/2016/03/01/migrations-are-versioned-in-rails-5.html

    Rails 5 为迁移类添加了一个版本,因此:

    Rails 5.0 中生成的迁移:

    class CreateTasks < ActiveRecord::Migration[5.0]
     ...
    end
    

    如果您没有它,它将尝试向我们提供兼容层。虽然该兼容性层针对的是 Rails 4.2,并且根据那篇文章它应该默认使用,但我会尝试将您的迁移更改为全部使用:

    class AddDevelopmentPlanToObjectives < ActiveRecord::Migration[4.2]
      ....
    

    看看是否有帮助。如果不是,我会更改您的迁移以适应 v5.0 概述的更改

    class AddDevelopmentPlanToObjectives < ActiveRecord::Migration[5.0]
      def change
        add_reference :objectives, :development_plan, foreign_key: true
      end
    end
    
    class DropDevelopmentPlans < ActiveRecord::Migration[5.0]
      def change
        Objective.all.each do |objective|
          company = objective.owner.company
          company.cycles.create name: '4Q 2015', begin_at: Date.today, end_at: 1.year.from_now, current: true unless company.current_cycle
          company.reload
          objective.update cycle: company.current_cycle
        end
        remove_foreign_key :objectives, :development_plan
        remove_reference :objectives, :development_plan
        drop_table :development_plans
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 2013-06-11
      • 2017-09-06
      相关资源
      最近更新 更多