我的格式如下:
<%= 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">
<%= text_input u, :first_name, class: "form-control", required: true %>
<%= label u, :first_name %>
<%= error_tag u, :first_name %>
</div>
<div class="row">
<%= text_input u, :last_name, class: "form-control", required: true %>
<%= label u, :last_name %>
<%= error_tag u, :last_name %>
</div>
<% end %>
<% end %>
我的控制器动作:
case Organizations.create_organization(params["organization"], plan) do
{:ok, %{user: user}} ->
...
{:error, _resource, changeset, _changes} ->
conn
|> put_status(:unprocessable_entity)
|> put_flash(:error, "Hmm, that didn't work. Please see the errors below.")
|> render("new.html", changeset: changeset)
end
无效变更集示例:
#Ecto.Changeset<
action: :insert,
changes: %{
name: "test",
owner: #Ecto.Changeset<
action: :insert,
changes: %{
email: "test@test.com",
first_name: "asdf",
id: nil,
last_name: "asdfasdf",
password: "testtest",
password_confirmation: "testtest",
password_hash: "bla"
},
errors: [
email: {"has already been taken",
[constraint: :unique, constraint_name: "accounts_users_email_index"]}
],
data: #MyApp.Accounts.User<>,
valid?: false
>
},
errors: [],
data: #MyApp.Organizations.Organization<>,
valid?: false
>
问题:当变更集无效时,将保留用户的名字,姓氏和电子邮件字段,但是organization[name]
字段将丢失先前输入的值。