Preload parent after build_assoc insert

Running on Phoenix 1.3-rc

I have a create action which insert a child (and belongs_to parent).

def create(conn, %{"parent_id" => parent_id, "child" => child_params}) do
  parent = Context.get_parent!(parent_id)

  with {:ok, %Child{} = child} <- Context.create_child(parent, child_params) do
    child = Repo.preload(child, :parent)

    conn
    |> put_status(:created)
    |> render("show.json", child: child)
  end
end

The Context.create_child(…) uses build_assoc to associate before inserting.
The View renders this to JSON, but I need to inline the parent.
My question regards preloading the parent, specifically:

child = Repo.preload(child, :parent)

Is there another way of doing this given I already get the parent initially?
Can I just put it back into the struct? Like this:

%Child{child | parent: parent}

Thanks!

1 Like

You should be able to do precisely that I would think, have you not tried it? :slight_smile:

1 Like

Yea it works. I was just wondering if there is another way.
I guess if you do any callbacks to update the parent, like touching it, you would have to re-fetch it anyway.

2 Likes

Precisely, all immutable, encode your state in your stack and all that. :slight_smile:

1 Like