dwyl / learn-phoenix-framework

:fire: Phoenix is the web framework without compromise on speed, reliability or maintainability! Don't settle for less. :rocket:
646 stars 45 forks source link

Multiple Schemas in one Phoenix Form #120

Open Danwhy opened 5 years ago

Danwhy commented 5 years ago

For club-soda we have a form where users can sign up and also add a venue to the site at the same time.

We have two separate schemas: User and Venue, and are using these to generate the inputs, with the attributes coming through to the controller in two separate maps: %{user: %{...}, venue: %{...}}.

This works, but the problem comes when there's a validation error in the form. For our normal forms with one schema, the data from the form is kept in the changeset, and so remains in the form when the page reloads, but for this form, we don't have a single changeset that contains both the venue and user data, so we either keep the venue data, the user data, or none.

Is there a way to use two changesets in one form?

It seems that the only way to go about this is to use nested changesets, whereby the Venue schema would belong to the User schema, or vice versa:

This does seem to make sense, as any data that is in one single form should be related, but is this the only way?