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)
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)
new_recipe = Repo.insert(recipe_changeset)
source
share