Managing Related Data

Our generated video controller gave us the CRUD basics, but as with any generated code, we’re going to need to tailor it to our needs. We want to link videos with users for this social platform. To do so, we need to grab the current user from the connection and scope our operations against the user. Open up your web/controllers/video_controller.ex, and let’s take a look at the new action:

 def​ new(conn, _params) ​do
  changeset = Video.changeset(%Video{})
  render(conn, ​"​​new.html"​, ​changeset:​ changeset)
 end

We need to change it so the video is built with the user_id pointing to the id of the user currently stored in the connection at conn.assigns.current_user. We know that the build_assoc function in Ecto

Get Programming Phoenix now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.