35

我正在尝试在我的 rails 4 应用程序中使用邮箱。当我尝试部署数据库时出现问题。创建邮箱会话表时发生错误,该表在通知表中具有依赖关系。

我正在尝试删除通知对话的外键。

我创建了一个迁移,它说:

change_table :notifications do |t|
t.remove_foreign_key :conversations

但是,rake 中止并说外键不存在。

rake aborted!
An error has occurred, this and all later migrations canceled:

PG::UndefinedObject: ERROR:  constraint "notifications_conversation_id_fk" of relation      "notifications" does not exist

我的架构包括:add_foreign_key “notifications”、“conversations”、名称:“notifications_on_conversation_id”

我试图 rake db:migrate:down 创建邮箱的原始迁移,但也收到一条错误消息,提示“找不到命令”。

任何人都可以帮忙吗?谢谢你。

4

3 回答 3

44
# Removes the given foreign key from the table.
# Removes the foreign key on +accounts.branch_id+.
remove_foreign_key :accounts, :branches

# Removes the foreign key on +accounts.owner_id+.
remove_foreign_key :accounts, column: :owner_id

# Removes the foreign key named +special_fk_name+ on the +accounts+ table.
remove_foreign_key :accounts, name: :special_fk_name

官方文档:http ://api.rubyonrails.org/v4.2/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_foreign_key

于 2017-05-03T04:22:47.090 回答
42

架构中的add_foreign_key命令为您的外键提供了 name notifications_on_conversation_id。此名称不同于外国人通常根据列名称分配的默认名称,即notifications_conversation_id_fk. 所以你的remove_foreign_key命令必须指定现有的外键名而不是列名。尝试:

remove_foreign_key :notifications, name: "notifications_on_conversation_id"
于 2014-05-18T13:01:39.890 回答
0

当我运行时,我得到了:

 NoMethodError: undefined method `remove_foreign_key' for #<ActiveRecord::ConnectionAdapters::Table:0x00007faa35e94aa8>
Did you mean?  remove_index

智慧之言 - 除了 id 整数外,不要使用任何东西作为外键。我在练习假应用程序时使用了标题参数,它导致:

ActiveRecord::AssociationTypeMismatch (Company(#70210936585940) expected, got "Company4" which is an instance of String(#70210933923380))
于 2019-01-27T09:12:46.343 回答