Rails5迁移:表没有外键

时间:2018-06-12 14:50:24

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

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

  

表&#39>目标'没有用于development_plan的外键

以下是重要的迁移:

  1. 使用add_reference

    创建foreign_key
    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
    
  3. remove_foreign_key :objectives, :development_plan

    上的迁移中断

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

2 个答案:

答案 0 :(得分:0)

参考这篇文章: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

答案 1 :(得分:0)

我相信 to_table 应该以复数形式倾斜:

remove_foreign_key :objectives, to_table: :development_plans

请参阅rails api docs