Idiomatic way to duplicate an Ecto.Changeset

I suspect any function on Ecto.Changeset is going to wind up doing things you don’t want - in this case, I’d recommend taking the simplest possible route and writing a function in Item that takes an Item and returns an unsaved Ecto.Changeset:

def duplicate(item) do
  changeset(%Item{}, %{title: item.title})
end

Reasoning:

  • you likely don’t want to copy some fields (ID, naturally; also probably inserted_at etc)

  • you might want to modify specific data - for instance, adding " (copy)" or similar to a title

  • you may need to do additional work to copy some fields (has_many associations, for instance)