Ecto: Casting% Plug.Upload for virtual field to check file downloads

I would like to be able to start downloading a file only when the changeset is valid and contains the file.

Is it possible / Good idea: a %Plug.Uploadeg

def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> save_image
end

defp save_image(changeset) do
  case changeset do 
    %Ecto.Changeset{valid?: true, changes: %{image: image}} ->
      %{ "url" => "http://" <> image_url } = Cloudinary.upload(image)
      put_change(changeset, :image_url, image_url)
    _ -> 
     changeset
 end
end

I tried installing :imagein a virtual field with a type :map, but it did not throw `% Plug.Upload

schema "model" do
  field :image_url, :string
  field :image, :map, virtual: true
  timestamps
end

It just causes a validation error with a message Image is invalid

+4
source share
2 answers

This will work, just find the virtual field type setting on :any

schema "model" do
  field :image_url, :string
  field :image, :any, virtual: true
  timestamps
end

, , , , / , , , .

+2

( ):

def save_image(model, params) do
  changeset = Model.changeset(model, params)
  case changeset.valid? do
    true ->
      %{ "url" => "http://" <> image_url } = Cloudinary.upload(params["file"])
      Model.image_changeset(changeset, image)
    _ -> changeset
  end
end

.

def image_changeset(changeset, image_url) do
  put_change(changeset, :image_url, image_url)
end
+4

Source: https://habr.com/ru/post/1616153/


All Articles