From 6530598b986d15f143930723d1237e55e4d149e5 Mon Sep 17 00:00:00 2001 From: yunmikun Date: Fri, 2 Oct 2020 15:31:04 +0300 Subject: [PATCH] Add ability to update image with existing data Suppose you have a loaded struct with already saved image and you want to put this image back into arguments. Now you are allowed to put this image back into arguments and expect it will be stored there without runtime errors. --- lib/waffle_ecto/schema.ex | 5 +++++ test/schema_test.exs | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/lib/waffle_ecto/schema.ex b/lib/waffle_ecto/schema.ex index 5c7f7d0..6eddc74 100644 --- a/lib/waffle_ecto/schema.ex +++ b/lib/waffle_ecto/schema.ex @@ -99,6 +99,11 @@ defmodule Waffle.Ecto.Schema do {field, upload = %{__struct__: Plug.Upload}}, fields -> [{field, {upload, scope}} | fields] + # Allow update with data from schema + {field, data = %{file_name: filename}}, fields + when is_binary(filename) -> + [{field, {data, scope}} | fields] + # Allow casting binary data structs {field, upload = %{filename: filename, binary: binary}}, fields when is_binary(filename) and is_binary(binary) -> diff --git a/test/schema_test.exs b/test/schema_test.exs index 8211036..aa78eb7 100644 --- a/test/schema_test.exs +++ b/test/schema_test.exs @@ -63,6 +63,16 @@ defmodule WaffleTest.Ecto.Schema do %{file_name: "file.png", updated_at: _} = cs.changes.avatar end + test_with_mock "supports updating with already existing data", DummyDefinition, + store: fn {_, %TestUser{}} -> + {:ok, "file.png"} + end do + attrs = %{"avatar" => build_upload("/path/to/my/file.png")} + cs = TestUser.changeset(%TestUser{}, attrs) + assert {:ok, user} = Ecto.Changeset.apply_action(cs, :insert) + TestUser.changeset(user, %{"avatar" => user.avatar}) + end + test_with_mock "cascades storage error into an error", DummyDefinition, store: fn {%{__struct__: Plug.Upload, path: "/path/to/my/file.png", filename: "file.png"}, %TestUser{}} ->