Reputation: 8318
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.
Upvotes: 2
Views: 484
Reputation: 222040
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.
Upvotes: 3