Ectoモデル/レコードを複製する最も簡単な方法は何ですか?多くの材料とラベルが埋め込まれたサンプルレシピモデルがあります。
モデル
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
レシピレコードのクローン レシピレコードを複製し、新しいレシピレコードを挿入するための変更セットを作成するにはどうすればよいですか?
recipe = Repo.get(App.Recipe, 1)
recipe_changeset = Ecto.Changeset.change(recipe)
# ... Steps for cloning record with embeds?
new_recipe = Repo.insert(recipe_changeset)
レシピと材料を複製し、新しいレシピIDを材料に割り当てます
新しい成分を含む新しいレシピレコードを挿入するために、事前にロードされた成分を含むレシピレコードを複製するにはどうすればよいですか?
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)
回答:
回答№1は0再度挿入する前にIDを削除してください。
Repo.get(App.Recipe, 1)
|> Repo.preload(:ingredients)
|> whatever_you_wanna_do
|> Map.delete(:id)
|> Repo.insert