更改变更集

Change a changeset

我不明白如何更改给定变更集的值。

设置

mix phoenix.new shop
cd shop
mix ecto.create
mix phoenix.gen.html Product products name price:integer
mix ecto.migrate

web/router.ex

[...]
scope "/", Shop do
  pipe_through :browser # Use the default browser stack

  get "/", PageController, :index
  resources "/products", ProductController
end
[...]

问题

我启动 IEX 并创建一个新的变更集:

iex -S mix phoenix.server
iex(1)> alias Shop.Product
iex(2)> changeset = Product.changeset(%Product{price: 1})
#Ecto.Changeset<action: nil, changes: %{},
 errors: [name: {"can't be blank", [validation: :required]}],
 data: #Shop.Product<>, valid?: false>

我现在如何更改给定的变更集?以下代码不起作用:

iex(3)> changeset = Product.changeset(changeset, %{name: "Orange"})
#Ecto.Changeset<action: nil, changes: %{name: "Orange"},
 errors: [name: {"can't be blank", [validation: :required]}],
 data: #Shop.Product<>, valid?: false>

由于错误,我现在无法 Shop.Repo.insert(changeset)

我知道在这个具体示例中我可以更改 iex(2) 行以获得我想要的变更集。但我想知道如何在创建变更集后对其进行操作。

Product.changeset(changeset.data, Map.merge(changeset.changes, %{name: "Orange"})) 就可以了。感谢 Dogbert.

$ iex -S mix phoenix.server
iex(1)> alias Shop.Product
Shop.Product
iex(2)> changeset = Product.changeset(%Product{price: 1})
#Ecto.Changeset<action: nil, changes: %{},
 errors: [name: {"can't be blank", [validation: :required]}],
 data: #Shop.Product<>, valid?: false>
iex(3)> changeset = Product.changeset(changeset.data, Map.merge(changeset.changes, %{name: "Orange"}))
#Ecto.Changeset<action: nil, changes: %{name: "Orange"}, errors: [],
 data: #Shop.Product<>, valid?: true>
iex(4)>