I created a simple "Thing" ecto model in Phoenix. The "image" is a string that references a file that gets uploaded. When an uploaded image hits the controller, I'd like to transform the image struct into a string (for the sake of this example, let's save it as "foo123")
#/web/models/thing.ex
defmodule MyApp.Thing do
use MyApp.Web, :model
schema "comics" do
field :number, :integer
field :image, :string
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:number, :image])
|> validate_required([:number, :image])
end
end
#/web/controllers/thing_controller.ex
def create(conn, %{"thing" => thing_params}) do
IO.inspect thing_params
changeset = Thing.changeset(%Thing{}, thing_params)
|> change("image", "foo123") ### something like this
case Repo.insert!(changeset) do
{:ok, _thing} ->
conn
|> put_flash(:info, "Thing created successfully.")
|> redirect(to: thing_path(conn, :index))
{:error, changeset} ->
conn
|> put_flash(:error, "Something went wrong")
|> redirect(to: thing_path(conn, :index))
end
end
This doesn't work, I still need to transform %{"image" => %Plug.Upload{content_type: "image/jpeg",...
into "foo123", but where does that happen? In the changeset assignment? In the parameters for def create()
?
Also, how can I IO.inspect
just a certain member of the param struct? (Like, IO.inspect thing_params.image
?
IO.inspect thing_params["image"]
..image
won't work because the key is a string, not an atom. – Dogbert|> put_change(:image, "foo123")
but that won't re-run the validations ofThing.changeset/2
. I'm not sure what the best way to handle file uploads manually is so I'm just commenting here instead of posting an answer. – Dogbertchangeset = Thing.changeset(%Thing{}, thing_params) |> put_change(:image, "foo123")
, I get** (CompileError) web/controllers/thing_controller.ex:19: undefined function put_change/3
. Is this the wrong place for it, or did I forget to import something into the controller? – Mark Karavan