Alexander Popov
Alexander Popov

Reputation: 24875

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?

Upvotes: 5

Views: 3649

Answers (1)

edwardmp
edwardmp

Reputation: 6591

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.

Upvotes: 1

Related Questions