Passing foreign key constraint before creating a parent object with “accepts_nested_attributes_for” and “inverse of”.
That is a little tricky.
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.
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.
has_many :children, foreign_key: 'parent_id', inverse_of: :parent
belongs_to :parent, inverse_of: :children
Save should come off !