Programming Phoenix pg 102 > changeset in "new"

Hi,

I’m wondering if anyone can shed any light on this. I’m working through the Programming Phoenix book, and am enjoying myself so far - I’ve learned a whole bunch, it’s a great book.

Now, on page 102 I’m adding the following:

  def new(conn, _params) do
    changeset = 
      conn.assigns.current_user
      |> build_assoc(:videos)
      |> Video.changeset()

   render(conn, "new.html", changeset: changeset)
 end

The idea here - as I understand it - is to generate a changeset that ties the logged in user to the Video that will be created when the user submits their form.

What I don’t understand is why do this at all in “new” ?

It makes sense to me that this would be done on POST / in the “create” function. And reading ahead this association is repeated in the “create” function.

As best I can see, doing this in “new” has no impact on the generated HTML.

What am I missing here?

Any help gratefully appreciated.

Thanks,

Chris

In your HTML form you use helper functions that build a proper form based on the structs ( %Video{} ) changeset that is passed to that helper functions. You don’t have to build that changeset at all, but then you would have to build the form by hand from grounds up.

1 Like

thanks for your reply @sztosz.

I understand about passing in the changeset, but I don’t understand the need for the build_assoc call in this changeset, as the relation to the current user seems to have no impact on the generated form code. Also, this association is done again when the form is submitted / POSTed to the ‘create’ route.

Maybe I’m over thinking it.