Created
October 23, 2018 13:27
-
-
Save kdiogenes/524ce8e13ff3d52558cc0150bf5e2562 to your computer and use it in GitHub Desktop.
phoenix: enforce field in changeset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def changeset(model, params \\ %{}) do | |
model | |
|> cast(params, [:name, :email] ++ coherence_fields()) | |
|> enforce_api_token | |
|> validate_required([:name, :email]) | |
|> validate_format(:email, ~r/@/) | |
|> unique_constraint(:email) | |
|> unique_constraint(:api_token) | |
|> validate_coherence_assent(params) | |
end | |
defp enforce_api_token(changeset) do | |
if changeset.data.api_token == nil do | |
changeset |> put_change(:api_token, (:crypto.strong_rand_bytes(32) |> Base.encode64 |> binary_part(0, 32))) | |
else | |
changeset | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment