迁移此迁移
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)
我的
order_items
表确实有order_id
列(并且已被编入索引)并且我有orders
表,但是为什么不是rails找到列order_id
放下它?
我暂时解决了
remove_index :order_items, :order_id
remove_column :order_items, : order_id
但如果我必须向下迁移add_reference
该怎么办?
答案 0 :(得分:1)
order_items
表包含order_id
列和索引index_order_items_on_order_id
。
但它没有外键,因为错误已明确说明。
如果存在如图所示,那么在数据库中进行交叉检查(有许多工具可用)。外键是 fk_rails_hash
形式的外键在我的情况下,外键在不正确的导出转储期间丢失,当我导入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