I have a couple of Ecto records. But I want to duplicate them (make them 100 times bigger) to play with big amount of records. How can I do that via ecto mechanisms?
You can replicate dup
by simply removing the id key from the record:
for n <- (0..10), do: User |> Repo.get(record_id) |> Map.delete(:id) |> Repo.insert
Although that won't work if you have unique keys... that would leave you needing to populate the struct yourself:
def spawn_records(line_numbers) do
for line <- line_numbers do
%User{first_name: "Tyrone", last_name: "Shoelaces#{line}"} |> Repo.insert
end
end
If you're thinking of that second answer I'd echo Dogbert and recommend using ex_machina in dev.
After I stripped the :id, I ran into an issue while attempting to insert because I didn't preload my associations. I shouldn't have to do that if I'm just duplicating the record, so I came up with this method. This assumes you have your schema's required and optional fields defined as constants in your module:
@required_fields [:id, :name, :association_id]
@optional_fields [:other_field]
def duplicate(record) do
dup = Map.take(record, @required_fields ++ @optional_fields)
changeset(%YourModule{}, dup)
|> Repo.insert!
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With