Insert child in a one to many relationship

Ecto for Beginners : part 16 of 22 published on Sep 07, 2015
# /test/models/comments/insert_test.exs
defmodule Readdit.Comments.InsertTest do
  use ExUnit.Case
  use Readdit.ConnCase 
end
test "insert! comment" do
    post = %Readdit.Post{title: "Han Shot First"} |> Readdit.Repo.insert!

    comment = %Readdit.Comment{
      content: "OMG first comment!",
      post_id: post.id
    } |> Readdit.Repo.insert!

    post = Readdit.Post |> Readdit.Repo.get(post.id)

    assert post.title == "Han Shot First"
    assert Enum.count(post.comments) == 1
  end

If we run our test now, we should get the following error.

** (Protocol.UndefinedError) protocol Enumerable not implemented for #Ecto.Association.NotLoaded<association :comments is not loaded>

The error is informing us that the :comments association is not loaded. We can load comments by replacing:

post = Readdit.Post |> Readdit.Repo.get(post.id)

With:

post = Readdit.Post 
  |> Readdit.Repo.get(post.id) 
  |> Readdit.Repo.preload(:comments)

Now if we run our tests we should pass.

Next: Many to Many relationship