2016-07-20 7 views
0

EctoとAmazon S3のエリクシルArcを使用して、以前ダウンロードしたファイルを保存しています。すべてが機能しているように見えますが、S3になります。しかし、私のデータベースには何も保存されていません。したがって、URLを生成しようとすると、常にデフォルトのURLが返されます。Elixir Arc:ファイルがアップロードされ、処理されますが、データベースに保存されません。

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 

答えて

2

だから、これに対する答えは2つある。まず第一に私のユーザモジュールのからavatarを削除しなければならなかった。

@optional_fields ~w() 

第2に、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) 

編集:より多くのエリクサーのように

avatar_params = %{avatar: "/tmp/my_file.jpg"} 
Repo.get(User, 1) |> User.changeset(avatar_params) |> Repo.update() 
関連する問題