mô hình của tôi:Accepts_nested_attributes_for tăng ActiveRecord :: InvalidForeignKey: PG :: ForeignKeyViolation: ERROR
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
Khi tôi cố gắng tạo ra các hồ sơ như sau:
Foo.create(foo_attribute: value, bars_attirbutes: [{bar_attribute: value}])
tôi nhận được:
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".
Vì vậy, tôi đoán ActiveRecord đang cố gắng lưu mô hình lồng nhau trước khi mô hình gốc được lưu và do đó các erro r. Nhưng tại sao nó lại làm điều này? Làm thế nào tôi có thể ngăn chặn nó làm điều này?