Why is params_for not going through the changeset?

218 views Asked by At

Why is params_for not going through the changeset model is the main question. params_for generates 4 digits and 2 letters for postal_code (could be lowercase or uppercase). If the params_for would be going trough the changeset, it would be all uppercase afterwards. Why does this test currently fail?

Error message: Expected truthy, got nil

I've a company model, with this changeset:

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

I have this test:

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 docs: https://hexdocs.pm/ex_machina/ExMachina.Ecto.html#c:params_for/2

1

There are 1 answers

0
Toby Hinloopen On BEST ANSWER

if params contains lowercased postal_code, it gets upcased by the changeset. However, Repo.get_by(Company, params) still looks for the lowercase postal code, returning nil