Create a Form with Multiple Associations

Learn how to create a Phoenix form with multiple associations.

Add support for multiple addresses

Let’s take this one step further. In the last example, we worked with a single address via the embeds_one association. Let’s try adding support for multiple addresses (embeds_many).

The process is similar to having a single address. The inputs_for function is smart enough to handle associations with one record or many records—it will always generate as many subforms as needed. So if, for example, we had two addresses associated with the user record, inputs_for would create two subforms, one for each address.

A problem: how to add a new address?

There’s just one problem—we don’t have a way for users to add a new address.

Think about how things work with just one address. When users first fill out the form, the address fields are blank. When users complete the form successfully and come back to it later, the form fields contain the data they entered before and they can make edits if they wish. With multiple addresses, we have to consider two possibilities.

  • Editing an existing address.
  • Creating a new one.

Get hands-on with 1200+ tech skills courses.