Why build an association for the "new" action?

Hi there,

I’m currently learning Phoenix by working through the Programming Phoenix book.
In chapter 6, Managing Related Data, it tells me to adjust the new action’s changeset like so:

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

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

As the new action only shows the form for creating a new video, I’m wondering why I have to build the association here? I’ve tried to use changeset = Video.changeset(%Video{}) here, and it works great, as the association will be build before inserting the video in the create action.

I’m also wondering where the data would be stored between requests when building the association in the new action.

Can someone explain this?

Thanks!

I ‘think’ it might be in case your form has an input area to create associations for the record, which if it does not then would not matter?

There is no advantage in doing this when the relationships between your data models is simple. If at some point it becomes more complicated; if, in your example for instance, the video form would be different depending what user was making it (say an administrator-user would have more options), then it becomes useful.

To do it this way right now is thus not required at all, but it can be a very easy way to make it easier to expand upon your code at a later time.

Of course, you yourself have to be the judge of when this is useful, and when YAGNI(You Aren’t Gonna Need It) applies.

2 Likes