What if I shuffle the order of functions inside a changeset function?

What if I shuffle the order of functions (piped into each other) inside the following changeset function?

  def changeset(%Customer{} = customer, attrs) do
    customer
    |> cast(attrs, [:name, :email, :residence_area, :password, :phone])
    |> validate_required([:name, :email, :residence_area, :password])
    |> validate_format(:email, ~r/@/, message: "is invalid")
    |> validate_length(:password, min: 6, max: 100)
    |> unique_constraint(:email)
    |> put_hashed_password()
  end

(example from Phoenix inside out)

Note: The last function put_hashed_password() is a private function which uses Comeonin library to hash my password.

In your example, you must put cast and put_hashed_password at their original position, and are free to put rest of the functions in any order.
The reason is that the first item actually puts the values inside the %Ecto.Changeset{}, and you cannot run validations on the %Changeset{} if you don’t first cast those values into the %Changeset{} (if the %Changeset{} is empty), and you’ll put_hashed_password into the %Changeset{} just before you’re entering it to the database, because you will check the original password’s length etc, not the hashed password’s.

I hope it helps!

1 Like

Yes, I changed the order of all of the functions and left the cast() and put_hashed_password() at their original positions (first and last), the tests passed. When I moved either cast() or put_hashed_password(), the tests failed. So it means you are right.
Thank you!

1 Like