我正在使用Elixirs Arc与Ecto和Amazon S3来存储我之前下载过的文件。一切似乎都有效,他们最终在S3。但我的数据库中没有存储任何内容。因此,如果我尝试生成一个URL,我总是只能获得默认的URL。
这是我存储文件的方式:
iex > user = Repo.get(User, 3)
iex > Avatar.store({"/tmp/my_file.png", user})
{:ok, "my_file.png"}
但user.avatar
字段仍为零。
我的用户模块:
defmodule MyApp.User do
use MyApp.Web, :model
use Arc.Ecto.Schema
alias MyApp.Repo
schema "users" do
field :name, :string
field :email, :string
field :avatar, MyApp.Avatar.Type
embeds_many :billing_emails, MyApp.BillingEmail
embeds_many :addresses, MyApp.Address
timestamps
end
@required_fields ~w(name email)
@optional_fields ~w(avatar)
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> cast_embed(:billing_emails)
|> cast_embed(:addresses)
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> unique_constraint(:email)
|> cast_attachments(params, [:avatar])
end
end
阿凡达上传者:
defmodule MyApp.Avatar do
use Arc.Definition
# Include ecto support (requires package arc_ecto installed):
use Arc.Ecto.Definition
@acl :public_read
# To add a thumbnail version:
@versions [:original, :thumb]
# Whitelist file extensions:
def validate({file, _}) do
~w(.jpg .jpeg .gif .png) |> Enum.member?(Path.extname(file.file_name))
end
# Define a thumbnail transformation:
def transform(:thumb, _) do
{:convert, "-strip -thumbnail 250x250^ -gravity center -extent 250x250 -format png", :png}
end
def transform(:original, _) do
{:convert, "-format png", :png}
end
def filename(version, {file, scope}), do: "#{version}-#{file.file_name}"
# Override the storage directory:
def storage_dir(version, {file, scope}) do
"uploads/user/avatars/#{scope.id}"
end
# Provide a default URL if there hasn't been a file uploaded
def default_url(version, scope) do
"/images/avatars/default_#{version}.png"
end
end
答案 0 :(得分:2)
所以答案是双重的。首先,我必须从用户模块中的avatar
中删除optional_fields
。
@optional_fields ~w()
其次,您不直接致电Avatar.store
,而是使用变更集。
avatar_params = %{avatar: "/tmp/my_file.jpg"}
user = Repo.get(User, 1)
avatar_changeset = User.changeset(user, avatar_params)
Repo.update(avatar_changeset)
修改:更多Elixir方式:
avatar_params = %{avatar: "/tmp/my_file.jpg"}
Repo.get(User, 1) |> User.changeset(avatar_params) |> Repo.update()