Reputation: 6571
On my app's signup page, I'm trying to use nested forms (using form_for/3 and inputs_for/4) in conjunction with Ecto.Multis and changesets.
Goal: To re-render the form with previously-entered information if one or more server-side validations fail, so that the user can make corrections as opposed to starting from scratch.
The app has an Organization schema, which has one User who is the creator/owner:
schema "organizations" do
field :owner_id, :integer
has_one :owner, MyApp.Accounts.User, references: :owner_id, foreign_key: :id
end
The Organizations context has this create_organization
function:
def create_organization(org_attrs, user_attrs) do
Ecto.Multi.new()
|> Ecto.Multi.insert(:organization, organization_changeset(%Organization{}, org_attrs))
|> Ecto.Multi.run(:user, fn _repo, %{organization: organization} ->
%User{organization_id: organization.id}
|> Accounts.register_user_changeset(user_attrs)
|> Repo.insert()
end)
|> Ecto.Multi.run(:update_organization, fn(_repo, %{user: user, organization: organization}) ->
organization
|> organization_creator_changeset(%{owner_id: user.id})
|> Repo.update()
end)
|> Repo.transaction()
end
(The reason I'm using an Ecto.Multi for this is because if, for instance, the user insertion fails, I want the entire operation to be rolled back.)
My controller actions:
def new(conn, _params) do
changeset = Organizations.create_organization_changeset(%Organization{owner: %User{}})
conn
|> render("new.html", changeset: changeset)
end
def create(conn, %{"organization" => %{"owner" => user_params}} = org_params) do
case Organizations.create_organization(org_params, user_params) do
{:ok, %{user: user}} ->
conn
|> put_status(:created)
|> put_view(MyAppWeb.Accounts.AccountView)
|> render("confirm.html", email: user.email)
{:error, _resource, changeset, _changes} ->
conn
|> put_status(:unprocessable_entity)
|> put_flash(:error, MyAppWeb.ErrorHelpers.transform_errors(changeset))
|> render("new.html", changeset: changeset)
end
end
And my form:
<%= form_for @changeset, account_path(@conn, :create), fn f -> %>
<div class="row">
<%= text_input :organization, :name, class: "form-control", required: true %>
<%= label f, :organization_name %>
<%= error_tag f, :name %>
</div>
<%= inputs_for f, :owner, fn u -> %>
<div class="row">
<%= email_input u, :email, class: "form-control", required: true %>
<%= label u, :email %>
<%= error_tag u, :email %>
</div>
<div class="row">
<%= password_input u, :password, class: "form-control", pattern: ".{8,}", title: "Password must have 8 or more characters.", required: true %>
<%= label u, :password %>
<%= error_tag u, :password %>
</div>
<div class="row">
<%= password_input u, :password_confirmation, class: "form-control", required: true %>
<%= label u, :password_confirmation %>
<%= error_tag u, :password_confirmation %>
</div>
<% end %>
<% end %>
The Problem: If everything goes well, the organization and the user are created successfully and confirm.html renders. However, if there are changeset errors, I get this:
could not generate inputs for :owner from MyApp.Accounts.User. Check the field exists and it is one of embeds_one, embeds_many, has_one, has_many, belongs_to or many_to_many
I believe this is because the Ecto.Changeset that is passed into new.html is a stand-alone %User{} changeset:
#Ecto.Changeset<
action: :insert,
changes: %{
email: "[email protected]",
organization: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
data: #MyApp.Organizations.Organization<>, valid?: true>,
password: "test",
password_confirmation: "test",
password_hash: "bla"
},
errors: [
email: {"has already been taken",
[constraint: :unique, constraint_name: "accounts_users_email_index"]}
],
data: #MyApp.Accounts.User<>,
valid?: false
>
What is the best way to solve this problem?
Upvotes: 1
Views: 604
Reputation: 121010
Instead of introducing your own reimplementation for inserting several nested / related records into different tables, you probably should better go with what Ecto
provides out of the box: Ecto.Changeset.put_assoc/4
in User
’s changeset.
It will perform all the validations for you and return a not valid changeset
is something went wrong.
Upvotes: 0