My models:
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
When I try to create records like so:
Foo.create(foo_attribute: value, bars_attirbutes: [{bar_attribute: value}])
I get:
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".
So I guess ActiveRecord is trying to save the nested model before the parent model is saved and hence the error. But why is it doing this? How can I prevent it from doing this?
I experienced a similar issue today. In my case, the issue is caused because I consolidated 2 tables into 1 (single table inheritance) by creating a new table, but had forgotten to drop the two old tables.
I still had other tables having foreign key constraints on these old two tables. Update or remove those foreign key constraints and you should be good to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With