Rails Postgres Schema引用回滚问题

时间:2016-04-12 18:21:34

标签: ruby-on-rails postgresql database-schema rails-migrations

在我的rails应用程序中,我有多个postgresql架构。

SHOW search_path;

search_path
--------------
"$user",public,vehicle

我在车辆架构中有两个表(经销商,库存)。这种关系是这样的:

dealer has_many inventories
inventory belongs_to dealer

我创建了一个迁移,将关系添加为:

class AddDealerIdToVehicleInventories < ActiveRecord::Migration
  def change
    add_reference 'vehicle.inventories', :dealer, index: true, foreign_key: {on_delete: :cascade}
  end
end

当我运行rake db:migrate时,此迁移工作正常,外键似乎没有任何问题地添加到表中。但是当我运行rake db:rollback时,我收到此错误消息:

StandardError: An error has occurred, this and all later migrations canceled:

PG::UndefinedColumn: ERROR:  column "vehicle.dealer_id" referenced in foreign key constraint does not exist
: ALTER TABLE "vehicle"."inventories" ADD CONSTRAINT "fk_rails_95ee16593d"
FOREIGN KEY ("vehicle.dealer_id")
  REFERENCES "vehicle"."dealers" ("id")
 ON DELETE CASCADE

我不确定我是否犯了任何错误,或者是rails迁移错误。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我通过在迁移文件中进行更改来解决此问题:

class AddDealerIdToVehicleInventories < ActiveRecord::Migration
  def up
    add_reference 'vehicle.inventories', :dealer, index: true, foreign_key: {on_delete: :cascade}
  end

  def down
    execute <<-SQL
      ALTER TABLE vehicle.inventories
        DROP COLUMN dealer_id
    SQL
  end
end

希望,这对其他人也很有用。