gpt4 book ai didi

ruby-on-rails - remove_reference 和 add_reference 的向下迁移报告没有外键

转载 作者:行者123 更新时间:2023-12-04 06:31:01 24 4
gpt4 key购买 nike

向上迁移这个迁移

def change
remove_reference :order_items, :order, foreign_key: true
end

或向下迁移此迁移

def change
add_reference :order_items, :order, foreign_key: true
end

抛出这个错误:

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

Table 'order_items' has no foreign key for {:to_table=>"orders"}
G:/Rails/learn_rails/db/migrate/20170222035809_move_order_items_under_restaurant_orders.rb:3:in `change'
G:/Rails/learn_rails/bin/rails:4:in `require'
G:/Rails/learn_rails/bin/rails:4:in `<top (required)>'
-e:1:in `load'
-e:1:in `<main>'
ArgumentError: Table 'order_items' has no foreign key for {:to_table=>"orders"}
G:/Rails/learn_rails/db/migrate/20170222035809_move_order_items_under_restaurant_orders.rb:3:in `change'
G:/Rails/learn_rails/bin/rails:4:in `require'
G:/Rails/learn_rails/bin/rails:4:in `<top (required)>'
-e:1:in `load'
-e:1:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

My order_items table does have order_id column (and it is indexed) and I do have orders table, but then why isn't rails finding the column order_id and dropping it?

我暂时解决了

remove_index :order_items, :order_id
remove_column :order_items, : order_id

但是如果我必须向下迁移 add_reference 我该怎么办?

最佳答案

order_items 表有 order_id 列和索引 index_order_items_on_order_id

但它没有 FOREIGN KEY,因为错误已明确指出。

如果如图所示存在,请在数据库中进行交叉检查(有许多可用工具)。外键是 fk_rails_hash

形式的外键

enter image description here

在我的例子中,外键在不正确的导出转储期间丢失,当我导入那个 sql_dump 并将我的数据迁移到这个数据库时,它们不存在,尽管索引和列被保留了。

解决方案:

  • 以正确的方式删除列和添加引用

    remove_index :order_items, :order_id
    remove_column :order_items, :order_id
    add_reference :order_items, :order, foreign_key: true

    # or add only the foreign the key constraint
    # i'm afraid it I would miss anything else doing so
  • 如果缺少这么多外键,最佳解决方案

    # instead of whole sql_dump
    # export only the data

    rails db:migrate:reset

    # import only the data making sure the insert
    # happens in the right order as it may violate
    # foreign_key constraints that are newly added

关于ruby-on-rails - remove_reference 和 add_reference 的向下迁移报告没有外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com