Ale*_*pov 5 activerecord ruby-on-rails nested-attributes
我的模特:
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
Run Code Online (Sandbox Code Playgroud)
当我尝试创建这样的记录时:
Foo.create(foo_attribute: value, bars_attirbutes: [{bar_attribute: value}])
Run Code Online (Sandbox Code Playgroud)
我明白了:
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".
Run Code Online (Sandbox Code Playgroud)
所以我想ActiveRecord试图在保存父模型之前保存嵌套模型,从而导致错误.但为什么这样做呢?我怎么能阻止它这样做呢?
我今天遇到了类似的问题。就我而言,导致该问题的原因是我通过创建新表将 2 个表合并为 1 个表(单表继承),但忘记删除两个旧表。
我还有其他表对这两个旧表具有外键约束。更新或删除这些外键约束,您就可以开始了。
| 归档时间: |
|
| 查看次数: |
3505 次 |
| 最近记录: |