Using storage_dir in Waffle and Waffle Ecto

# My AvatarUploader
# Override the storage directory:
def storage_dir(_version, {_file, scope}) do
  "uploads/user/avatars/#{scope.id}"
end
# My User schema
use Waffle.Ecto.Schema

  schema "users" do
    field :avatar, Allychat.Uploaders.AvatarUploader.Type
    field :email, :string
    field :password, :string, virtual: true, redact: true
    field :hashed_password, :string, redact: true
    field :confirmed_at, :naive_datetime

    timestamps()
  end

  def avatar_changeset(user, attrs) do
    user
    |> cast(attrs, [:avatar])
    |> cast_attachments(attrs, [:avatar])
    |> validate_required([:avatar])
  end
# My Accounts context
def change_user_avatar(user, attrs \\ %{}) do
  User.avatar_changeset(user, attrs)
end

def update_user_avatar(user, attrs) do
  changeset =
    user
    |> User.avatar_changeset(attrs)

  Ecto.Multi.new()
  |> Ecto.Multi.update(:user, changeset)
  |> Repo.transaction()
  |> case do
    {:ok, %{user: user}} -> {:ok, user}
    {:error, :user, changeset, _} -> {:error, changeset}
  end
end

When I do this, it tells me that it can’t find id in nil. I tried a lot of options, also the one from waffle_ecto docs, and still couldn’t find an answer on how to upload an image to the storage_dir.

Does anyone know what I can do to fix this? I’m pretty new to Waffle :slightly_smiling_face:

Can you try once with removing the avatar from first cast? My working config is like below and everything else is similar, so I’m not sure what else could be the problem apart from the user being an empty map.

 def avatar_changeset(user, attrs) do
    user
    |> cast(attrs, [])
    |> cast_attachments(attrs, [:avatar])
    |> validate_required([:avatar])
  end
1 Like

Hey, I did that and realised that my problem was in the image getting functions, not the ones that create it.

Everything works now :slightly_smiling_face:

1 Like

What was the fix you did? To fix it
Me also working on some waffle related stiff

1 Like

Hey, you can check out the changes I’ve made to fix it by reading the changes in this commit.

1 Like

I couldn’t visit the link because of authentication,
It showing 404 status when I click on the link

1 Like

Can you try it again now?

1 Like

Thank you, it’s opening now

2 Likes