为什么 params_for 没有通过变更集?
Why is params_for not going through the changeset?
为什么 params_for 不通过变更集模型是主要问题。 params_for 为 postal_code 生成 4 个数字和 2 个字母(可以是小写或大写)。如果 params_for 将通过变更集,则之后将全部大写。为什么此测试当前失败?
错误信息:Expected truthy, got nil
我有一个公司模型,有这个变更集:
def changeset(company, params \ %{}) do
company
...
|> maybe_sanitize_postal_code(:postal_code)
...
end
defp maybe_sanitize_postal_code(changeset, attr) do
case get_change(changeset, attr) do
nil -> changeset
postal_code -> put_change(changeset, attr, sanitize_postal_code(postal_code))
end
end
defp sanitize_postal_code(postal_code) do
postal_code
|> String.replace(~r/\s+/, "")
|> String.upcase()
end
我有这个测试:
test "create company with postal code", %{conn: conn, user: user} do
params = params_for(:company)
conn = post conn, company_path(conn, :create), company: params
assert json_response(conn, 201)["company"]["id"]
company = Repo.get_by(Company, params)
assert company
assert [user] == Repo.all Ecto.assoc(company, :users)
...
end
params_for 文档:https://hexdocs.pm/ex_machina/ExMachina.Ecto.html#c:params_for/2
如果 params
包含小写的 postal_code
,它会被变更集提升。但是,Repo.get_by(Company, params)
仍然查找小写的邮政编码,返回 nil
为什么 params_for 不通过变更集模型是主要问题。 params_for 为 postal_code 生成 4 个数字和 2 个字母(可以是小写或大写)。如果 params_for 将通过变更集,则之后将全部大写。为什么此测试当前失败?
错误信息:Expected truthy, got nil
我有一个公司模型,有这个变更集:
def changeset(company, params \ %{}) do
company
...
|> maybe_sanitize_postal_code(:postal_code)
...
end
defp maybe_sanitize_postal_code(changeset, attr) do
case get_change(changeset, attr) do
nil -> changeset
postal_code -> put_change(changeset, attr, sanitize_postal_code(postal_code))
end
end
defp sanitize_postal_code(postal_code) do
postal_code
|> String.replace(~r/\s+/, "")
|> String.upcase()
end
我有这个测试:
test "create company with postal code", %{conn: conn, user: user} do
params = params_for(:company)
conn = post conn, company_path(conn, :create), company: params
assert json_response(conn, 201)["company"]["id"]
company = Repo.get_by(Company, params)
assert company
assert [user] == Repo.all Ecto.assoc(company, :users)
...
end
params_for 文档:https://hexdocs.pm/ex_machina/ExMachina.Ecto.html#c:params_for/2
如果 params
包含小写的 postal_code
,它会被变更集提升。但是,Repo.get_by(Company, params)
仍然查找小写的邮政编码,返回 nil