How can I copy a record to a new record with all associated records.
I have a Template, that has Fields and Keywords associations.
Template
→ Fields
→ Keywords
I want to create a duplicate of Template, and also duplicates of all associated records.
Tried with preloading everything and deleting :id so it signals as a new record.
It creates a new Template, but all associations are only moved to a new Template. I want to copy also all associations, beside user, which is on top of Template.
This will require more effort than the map-manipulation approach when adding new columns, but on the other hand it will never copy values that weren’t expected.
In other not to cause conflict when trying to clone the record , it’s best you make a soft copy by copying only the attributes you need and casting the attributes into a changeset, then inserting.
duplicate_record_from_target_recrod = fun target_record ->
#note don't include the id!
target_fields = [:fields,:keywords,:associated_record_id]
Template.changeset(Map.take(target_record, target_fields))
|> Repo.insert
end
USE CASE template = Template |> Repo.get(id) duplicate_record_from_target_recrod.(template) #create a new template with all associated records.