Passing foreign key constraint before creating a parent object with “accepts_nested_attributes_for” and “inverse of”.
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 !