Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone an Ecto record. With embeds and associated records?

What is the easiest way to clone an Ecto model / record? I have a sample recipe model with many ingredients and embedded labels.

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 changeset for inserting 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)

Clone recipe and ingredients and assign new recipe id to ingredients

How can I clone a recipe record with preloaded ingrediens for inserting a new recipe record 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)
like image 281
rodeinator Avatar asked Jun 30 '16 08:06

rodeinator


People also ask

What are embeds in Ecto?

Besides associations, Ecto also supports embeds in some databases. With embeds, the child is embedded inside the parent, instead of being stored in another table.

How to clone an opportunity record in Dynamics CRM?

So you need to add a new dataverse Trigger when a row is added and choose the opportunity record and then use an action Add a new row and choose opportunity and use the Dynamics mapping to clone the records. If this post helps you with your problem, please mark your as Accepted solution.If you like my response, please give it a Thumbs Up.

Is there a way to clone a record along with its relationships?

There's 3rd party tool called Snapshot from Cobalt to clone the record along with its relationships. But it doesn't work for N:N relationships. 1) you need to clone records by plugin / workflow so you are asking for a c# method?

How to clone an entity using the SDK?

1Create a flag field into the entity that you need to clone called “CloneRecord” of boolean type Develop and register a CRM c# plugin on the Update of that field. The plugin use the “EntityExtensions.Clone” method of the SDK to accelerate the copy of the entity You will need to clone the “header” and “details” of the quote (for our example).


1 Answers

Just remove the id before you insert it again.

Repo.get(App.Recipe, 1)
|> Repo.preload(:ingredients)
|> whatever_you_wanna_do
|> Map.delete(:id)
|> Repo.insert
like image 83
Mac Avatar answered Sep 27 '22 21:09

Mac