Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accepts_nested_attributes_for raises ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR

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?

like image 839
Alexander Popov Avatar asked Nov 10 '22 19:11

Alexander Popov


1 Answers

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.

like image 63
edwardmp Avatar answered Dec 08 '22 09:12

edwardmp