2
votes

A User has_many emails. How can I create a new User and have a single new Email nested in the form?

user_controller.ex

[...]
def new(conn, _params) do
  changeset = User.changeset(%User{})
  render(conn, "new.html", changeset: changeset)
end
[...]

form.html.eex

[...]
<%= inputs_for f, :emails, fn ef -> %>
  <div class="form-group">
    <%= label ef, :value, class: "control-label" %>
    <%= text_input ef, :value, class: "form-control" %>
    <%= error_tag ef, :value %>
  </div>
<% end %>
[...]

There are a couple of Stackoverflow questions about this but none fixes this simple problem.

1

1 Answers

3
votes

In the controller, use Ecto.Changeset.put_assoc/4:

alias MyApp.Email

[...]

changeset =
  User.changeset(%User{})
  |> Ecto.Changeset.put_assoc(:emails, [%Email{}])
render(conn, "new.html", changeset: changeset)

This will create one empty %Email with default values and put it in the :emails association of the changeset.