How/where to preload has_many relationship data in Phoenix 1.3

Viewed 428

I'm learning Elixir/Phoenix on a sample project and started with Phoenix 1.2. Now I recreated the project with Phoenix 1.3 to see/learn differences and adapt my old code.

In there I have a has_many relationship between a model Position and Skill. Whereas in the 1.2 code in position_controller.ex I used

case Repo.insert(changeset) do
  {:ok, position} ->
    position = position |> Repo.preload(:skills)
    ...

to have skills preloaded for rendering I'm unsure where to put this in my 1.3 code.

Controller seems to be the wrong place now (Repo isn't even known) so I placed it into my context file inside create_position like this:

def create_position(attrs \\ %{}) do
  with {:ok, %Position{} = position} <-
    %Position{}
    |> Position.changeset(attrs)
    |> Repo.insert() do

    position = Repo.preload(position, :skills)
    {:ok, position}
  end
end

Which feels strange since it now does more than just inserting.

So what is the correct and best way to perform this task?

1 Answers
Related