Giving a struct to Ecto.Repo.update/2 is not supported

Hi, the following code generates the error:

from(f in Foo,
  update: [inc: [count: 1]],
  where: f.id == ^foo.id
)
|> Repo.update!()

** (ArgumentError) giving a struct to Ecto.Repo.update/2 is not supported. Ecto is unable to properly track changes when a struct is given, an Ecto.Changeset must be given instead

How should I solve this?

Thank you for any help!

1 Like

:wave:

AFAIK, Repo.update works only with changesets. Try Repo.update_all instead.

from(f in Foo,
  update: [inc: [count: 1]],
  where: f.id == ^foo.id
)
|> Repo.update_all([])

or

from(f in Foo, where: f.id == ^foo.id)
|> Repo.update_all(inc: [count: 1])
2 Likes

Alternatively, you can create a changeset from any struct (and if you have updates to an existing struct, this is usually better since it will result in only the fields that actually were changed being part of the SQL query) using Ecto.Changeset.cast/3.

1 Like