I have a rails API that injects primary key IDs from the client, as opposed to autogenerating through Rails. Specifically:
class ParentModel < ApplicationRecord
accepts_nested_attributes_for: child_models
has_many :child_models
end
class ChildModel < ApplicationRecord
belongs_to :parent_model
end
Nested data is created via:
@parent_object = ParentModel.find_or_initialize_by(id: parent_model_params[:id])
@parent_object.assign_attributes(parent_model_params)
@parent_object.save
If the ID for a child_object already exists in the database, the operation updates the child object as expected. However, if the child object is new, I get:
Couldnt find ChildModel with ID=b35e8f02... for ParentModel with ID=0c9b60f3...
In short: I'm trying to ensure rails creates child records (with the given IDs) when they don't exist, and continues to update existing child records if they do. Any thoughts on how to do that through nested attributes?