Ecto - 更新嵌套嵌入

时间:2016-10-28 16:24:24

标签: elixir ecto

我无法使用ecto更新嵌套设置,我得到"没有更改"变更或错误。迁移:

def change do
  create table(:trees) do
  ...
  add :settings, :map

设置如下:

defmodule Final.TreeSettings do
  use Ecto.Schema

  embedded_schema do
    ...
    field :columns, :map       
    timestamps
  end
end

请注意嵌套列映射。

我可以轻松插入新的Tree行:

changeset = Tree.changeset(%Tree{}, %{user_id: user_id, name: x})
      |> Ecto.Changeset.put_embed(:settings, treeSettings)

但以同样的方式更新它并不起作用:

get_tree = Repo.one! from p in Tree, where: p.name == ^tree["name"], where: p.user_id == ^user_id
settingss = get_tree.settings
settingss = Kernel.update_in(settingss.columns[tree["setting"]][tree["type"]], fn x -> "asdasd" end)
# IO.inspect(settingss) shows correct changes here.
changeset =
    get_tree
    |> Ecto.Changeset.change
    |> Ecto.Changeset.put_embed(:settings, settingss)    
    IO.inspect changeset

给予:

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

1 个答案:

答案 0 :(得分:7)

我认为您可以在<servers> <server name="Server1" group="Group1" auto-start="true"> <jvm name="Server1_JVM" debug-enabled="false"> <heap size="2048m" max-size="4096m"/> <jvm-options> <option value="-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"/> </jvm-options> </jvm> <socket-bindings socket-binding-group="full-ha-sockets" port-offset="100"/> </server> </servers>

中使用之前将其嵌入 Ecto.Changeset.change/2

完整示例:

<强>迁移:

Ecto.Changeset.html#put_embed/4

模型树:

defmodule Final.Repo.Migrations.CreateTree do
  use Ecto.Migration

  def change do
    create table(:trees) do
      add :settings, :map
    end
  end
end

模型树设置:

defmodule Final.Tree do
  use Final.Web, :model

  schema "trees" do
    embeds_one :settings, Final.TreeSettings
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [])
    |> cast_embed(:settings)
  end
end

测试:

defmodule Final.TreeSettings do
  use Final.Web, :model

  embedded_schema do
    field :columns, :map
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:columns])
  end
end