Nested attributes in Phoenix (Live) Views:
To use nested attributes in a form you have to use the inputs_for
helper:
<%= f = form_for @changeset, Routes.user_path(@socket, :create), phx_submit: :submit, as: :user %>
<%= input f, :name %>
<%= inputs_for f, :address, fn a -> %>
<%= input a, :city %>
<%= input a, :zipcode %>
<% end %><
<%= submit "Create" %>
</form>
And then you can use cast_assoc
and specify the changeset for the nested schema you want to validate:
defmodule MyApp.User do
def registration_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:name])
|> cast_assoc(:address, with: &MyApp.Address.changeset/2)
|> validate_required([:name, :address])
end
end
defmodule MyApp.Address do
def changeset(address, attrs, opts \\ []) do
user
|> cast(attrs, [:city, :zipcode])
|> validate_required([:city, :zipcode])
end
end
Tweet