Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate records for Ecto?

Tags:

elixir

ecto

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?

like image 322
asiniy Avatar asked Aug 08 '16 10:08

asiniy


2 Answers

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.

like image 63
Mac Avatar answered Nov 03 '22 07:11

Mac


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
like image 32
Don Pflaster Avatar answered Nov 03 '22 08:11

Don Pflaster