abitdodgy

abitdodgy

  • Elixir 1.2
  • Phoenix 1.2.1
  • arc: 0.6.0
  • arc_ecto 0.5.0

According to the Phoenix documentation, if no file is selected, Plug.Upload will not be present in the params map.

Finally, notice that when there is no data from the file input, we get neither the “photo” key nor a Plug.Upload struct. Here are the user_params from the log.

So if you submit a blank form, params[:user] will be nil. For example:

<%= form_for @changeset, @action, [multipart: true], fn f -> %>
  <%= file_input f, :avatar %>
  <%= submit "Submit" %>
<% end %>

Notice the absence of the “user” key.

%{"_csrf_token" => "...", "_method" => "put", "_utf8" => "✓"}

Which raises an error in the controller.

bad request to App.Account.AvatarController.update, no matching action clause to process request
  def update(conn, %{"user" => user_params}, current_user) do
    changeset = User.avatar_changeset(current_user, user_params)
    case Repo.update(changeset) do
      {:ok, _} ->
        redirect(conn, to: current_user_avatar_path(conn, :edit))
      {:error, changeset} ->
        render(conn, :edit, changeset: changeset, user: current_user)
    end

We can hack around the error by including a hidden field in the form, forcing params[:user] to exist.

<%= hidden_input f, :id %>

But Plug.Upload will still be missing from the params. Which means the changeset will be valid. Notice changes being an empty map.

#Ecto.Changeset<action: nil, changes: %{}, errors: [], data: #App.User<>, valid?: true>

So, my questions are:

  1. What’s the point of |> validate_required([:avatar]) given that Plug.Upload is only present with file data? To reach this point in the changeset, a field must be present. It seems redundant then to validate for presence.
  2. How do we validate the presence of avatar?

Here’s my user schema:

defmodule App.User do
  use App.Web, :model
  use Arc.Ecto.Schema

  schema "users" do
    # ...
    field :avatar, App.AvatarUploader.Type
  end

  def avatar_changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:avatar])
    |> cast_attachments(params, [:avatar])
    |> validate_required([:avatar])
  end

Am I missing something?

Showing Posts 1 to 3

hubertlepicki

hubertlepicki

Well, you hit the thing I hate about validations in ORMs. You really do want to validate submitted form, and not validate the model, because of the reasons above. In my opinion, this really is the major design flaw, in Rails and by shared genes in Phoenix.

I tend to work around the issue by creating “Form objects” or “Form modules/structs” and handling validations outside of the “model” layer altogether. Which is more work, but has it’s rewards. Combination of GitHub - CargoSense/vex: Data Validation for Elixir · GitHub and GitHub - appcues/exconstructor: An Elixir library for generating struct constructors that handle external data with ease. · GitHub does the job for me at the moment. But this is radical approach, you may not want to take.

In your case, you can define 2nd function head in your controller, that will catch the nil. And it would call the current function you have, explicitly passing a nil to the avatar field, so the validations kick in properly.

michalmuskala

michalmuskala

You can use ecto to do pure form validations without database tables. You event don’t need to define schema modules - you only need the changeset function. I use ecto frequently to cover that use case - what you’d usually call “form objects” in Rails. José talks about how to do this in the free Ecto 2.0 ebook, I’m not sure about examples in the wild.

As to files uploads in general, I succumbed a long time ago - there are always issues and it never works correctly. I decided to do direct uploads from the browser to some storage service like s3 or cloudinary, only sending the upload url back to backend. I never looked back. It removes a whole bunch of issues.

abitdodgy

abitdodgy OP

@michalmuskala thanks. Cloudinary looks great. Can you think of other options (libs or services) for doing direct uploads from the browser to S3 or similar? In Rails, I use Refile, which allows multiple direct uploads to S3. Arc doesn’t seem to have matured yet. There is another lib that’s inspired by Refile, but it doesn’t pack as much functionality.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews