Passing foreign key constraint before creating a parent object with “accepts_nested_attributes_for” and “inverse of”.

Tomoharu Tsutsumi
1 min readJul 19, 2020

That is a little tricky.

Issue

When you are writing codes of rails, sometimes you face this issue. You want to save a parent object and child objects at the same time. However, if the objects have a foreign key constraint, it can’t be realized easily because when the child objects are being created, the parent_id is nil. Therefore, the codes result in an error.

Solution

If you want to the parent and child objects at the same time, you have to use “accepts_nested_attributes_for” and “inverse of” like below.

Class Parent 
has_many :children, foreign_key: 'parent_id', inverse_of: :parent
accepts_nested_attributes_for :children
end

and

class Child
belongs_to :parent, inverse_of: :children
end

Save should come off !

Started LinkedIn as well!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

--

--

Tomoharu Tsutsumi
Tomoharu Tsutsumi

Written by Tomoharu Tsutsumi

5+ years Full Stack SWE (Ruby, Go, TypeScript, JavaScript) | Former Founding Engineer of AI Startup in Canada

No responses yet