Sergio Tapia
Sergio Tapia

Reputation: 9823

Updating a field using Ecto one-liner?

In Ruby, I can go:

User.find_by(email: "[email protected]").update(email: "[email protected]")

How can I do something similar in Elixir?

Ecto.Changeset.change(MyApp.User |> where(email: "foobar"), email: "barbaz") |> MyApp.Repo.update

Upvotes: 1

Views: 871

Answers (2)

Sergio Tapia
Sergio Tapia

Reputation: 9823

You can do something like:

from(u in MyApp.User, where: u.email == "[email protected]") |> MyApp.Repo.update_all(set: [email: "[email protected]"])

Upvotes: 1

Dogbert
Dogbert

Reputation: 222198

You can use set: in a query and run it using Repo.update_all/1:

from(
  u in User,
  where: u.email == "[email protected]",
  update: [set: [email: "[email protected]"]]
) |> Repo.update_all([])

Upvotes: 0

Related Questions