gpt4 book ai didi

ruby-on-rails - Accepts_nested_attributes_for 引发 ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR

转载 作者:行者123 更新时间:2023-12-04 21:40:15 24 4
gpt4 key购买 nike

我的模型:

class Foo < ActiveRecord::Base
has_many :bars, inverse_of: :foo
accepts_nested_attributes_for :bars

...
end

class Bar < ActiveRecord::Base
belongs_to :foo, inverse_of: :bars

...
end

当我尝试像这样创建记录时:
Foo.create(foo_attribute: value, bars_attirbutes: [{bar_attribute: value}])

我得到:
ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  insert or update on table "bars" violates foreign key constraint "bars_foo_id_fkey"
DETAIL: Key (foo_id)=(14) is not present in table "foos".

所以我猜 ActiveRecord 试图在保存父模型之前保存嵌套模型,因此出现错误。但它为什么要这样做呢?我怎样才能防止它这样做?

最佳答案

我今天遇到了类似的问题。就我而言,问题是因为我通过创建新表将 2 个表合并为 1 个(单表继承),但忘记删除两个旧表。

我还有其他表对这两个旧表具有外键约束。更新或删除那些外键约束,你应该很高兴。

关于ruby-on-rails - Accepts_nested_attributes_for 引发 ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28496106/

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