Ecto:根据现有行

时间:2016-08-04 14:47:47

标签: elixir phoenix-framework ecto

我尝试复制带有更改的postgres行。 link是现有行。我尝试了各种排列,但无法创建变更集 - 欢迎提供帮助。

我正在使用此版本的ecto

:phoenix_ecto, "~> 3.0-rc"`

和此代码

        IO.inspect(link)
        changeset =
            link
            |> Map.from_struct
            # |> Map.delete(:id)
            |> Upload.persist_changeset(params)
        # new_link =
        #     Map.put link, :file_names, params["file_names"]
        # case Repo.insert new_link do
        case Repo.insert changeset do
            {:ok, link} ->
                render conn, "link.json", link: link.link
            {:error, changeset} ->
                ...
        end

  def persist_changeset(model, params \\ :empty) do
    model
    |> cast(params, ~w(upload_type file_names), ~w(job_id template_id estimate_ids))
  end

IO.inspect

%Api.Upload{__meta__: #Ecto.Schema.Metadata<:loaded, "uploads">,
 email: "hotbelgo@gmail.com", estimate_ids: [1],
 file_names: ["f1.pdf", "f2.pdf"], id: 8,
 inserted_at: #Ecto.DateTime<2016-08-04 10:01:21>,
 job: #Ecto.Association.NotLoaded<association :job is not loaded>, job_id: 1,
 link: "na2ClfJie4PsYC4y8Lr9",
 template: #Ecto.Association.NotLoaded<association :template is not loaded>,
 template_id: nil, updated_at: #Ecto.DateTime<2016-08-04 14:21:58>,
 upload_type: "Artwork"}

错误

  

**(FunctionClauseError)Ecto.Changeset.do_cast / 4中没有函数子句匹配

这是link

的方案
defmodule MosaicApi.Upload do
  use MosaicApi.Web, :model

  schema "uploads" do
    belongs_to :job, MosaicApi.Job
    belongs_to :template, MosaicApi.Template
    field :estimate_ids, {:array, :integer}

    field :upload_type, :string
    field :file_names, {:array, :string}

    field :link, :string
    field :email, :string

    timestamps
  end

1 个答案:

答案 0 :(得分:1)

我找到了解决方案,虽然我不确定这是最好的方法

        update_params =
            link
            |> Map.from_struct
            |> Map.put :file_names, params["file_names"]
            changeset =
                Upload.changeset(%Upload{}, update_params)