Search code examples
elixirphoenix-frameworkecto

Update multiple records using ecto 2.0


I could insert multiple records in ecto 2.0:

iex(1)> categories = [%{name: "stackoverflow", url: "stackoverflow.com"}]

iex(2)> App.Repo.insert_all App.Category, categories

Is it possible to update multiple records at once?

iex(1) > category = App.Repo.all(App.Category) |> hd

iex(2) > changeset = App.Category.changeset(category, %{name: "test"})

iex(3)> App.Repo.insert_all App.Category, [changeset]

I've a scenario where I've to insert or update categories everyday after crawling external pages. Seems like there is Multi feature in Ecto 2.0. Any pointers on how to go about this?


Solution

  • Just as there is an insert_all/3 function, there is also an update_all/3 function. update_all/3 takes a Queryable (%MyApp.SomeModel{} or a query), a Keyword List of updates ([name: "John"]), and an optional Keyword List of options.