Update all

Ecto for Beginners : part 20 of 22 published on Sep 07, 2015
# /test/models/posts/update_all_test.exs
defmodule Readdit.Posts.UpdateAllTest do
  use ExUnit.Case
  use Readdit.ConnCase
  import Ecto.Query

  setup do
    %Readdit.Post{
      title: "Han Shot First",
      topic: "Star Wars",
      votes: 4
    } |> Readdit.Repo.insert!

    %Readdit.Post{
      title: "R2D2 is the best!",
      topic: "Star Wars",
      votes: 6
    } |> Readdit.Repo.insert!
    
    %Readdit.Post{
      title: "Tony Stark is Iron Man",
      topic: "Marvel",
      votes: 12
    } |> Readdit.Repo.insert!

    %Readdit.Post{
      title: "Batman > Superman",
      topic: "DC",
      votes: 7
    } |> Readdit.Repo.insert!

    Readdit.Post
    |> where([p], p.topic == "Star Wars")
    |> Readdit.Repo.update_all(set: [votes: 200])

    :ok
  end

  test "updates all Star Wars posts" do
    posts = Readdit.Post
    |> where([p], p.topic == "Star Wars")
    |> Readdit.Repo.all

    Enum.each(posts, fn post ->
      assert post.votes == 200
    end)
  end

  test "does not update other posts" do
    posts = Readdit.Post
    |> where([p], p.topic != "Star Wars")
    |> Readdit.Repo.all

    Enum.each(posts, fn post ->
      assert post.votes != 200
    end)
  end

end
Next: Paging