首页 > 解决方案 > Rails5迁移:表没有外键

问题描述

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

表“目标”没有 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
    

迁移中断remove_foreign_key :objectives, :development_plan

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

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

解决方案


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

remove_foreign_key :objectives, to_table: :development_plans

请参阅rails api 文档


推荐阅读