O'Reilly logo

Programming Phoenix by Jose Valim, Bruce Tate, Chris McCord

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required