Skip to content

Instantly share code, notes, and snippets.

@elbow-jason
Created November 24, 2017 17:34
Show Gist options
  • Save elbow-jason/9f9c5dd3a1154476132648e6e136247c to your computer and use it in GitHub Desktop.
Save elbow-jason/9f9c5dd3a1154476132648e6e136247c to your computer and use it in GitHub Desktop.
insert changeset
now = DateTime.utc_now()
entries =
boxes
|> Enum.map(fn
%_{} = box ->
Map.from_struct(box)
%{} = attrs ->
attrs
end)
|> Enum.reduce([], fn attrs, acc ->
if %Box{} |> Box.changeset(attrs) |> Map.get(:valid?) do
attrs =
attrs
|> Map.put(:inserted_at, now)
|> Map.put(:updated_at, now)
[ attrs | acc ]
else
acc
end
end)
Turf.Repo.insert_all(Box, entries, on_conflict: :nothing, returning: true)
|> case do
{count, inserted_boxes} when count >= 0 and is_integer(count) ->
inserted_boxes
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment