Clone Ecto Record. Using attachments and related entries?

What is the easiest way to clone an Ecto model / record? I have a sample recipe with many ingredients and built-in shortcuts.

Model

defmodule App.Recipe do
use App.Web, :model

schema "recipes" do
  field :name, :string
  has_many :ingredients, App.Ingredient
  embeds_many :labels, App.Label
end

Clone Recipe Record How can I clone a recipe record and create a set of changes to insert a new recipe record?

recipe = Repo.get(App.Recipe, 1)
recipe_changeset = Ecto.Changeset.change(recipe)

# ... Steps for cloning record with embeds?  

new_recipe = Repo.insert(recipe_changeset)

Cloning Recipe and Ingredients and Assign a New Recipe Identifier to Ingredients

How can I clone a recipe entry with predefined ingredients to insert a new recipe entry with new ingredients?

recipe = Repo.get(App.Recipe, 1)
        |> Repo.preload(:ingredients)
recipe_changeset = Ecto.Changeset.change(recipe)

# ... Steps for cloning records?              

new_recipe = Repo.insert(recipe_changeset)
+4
source share
1 answer

Just remove the identifier before inserting it again.

Repo.get(App.Recipe, 1)
|> Repo.preload(:ingredients)
|> whatever_you_wanna_do
|> Map.delete(:id)
|> Repo.insert
0

All Articles