Skip to content

Instantly share code, notes, and snippets.

@meinac
Created March 12, 2016 21:30
Show Gist options
  • Save meinac/7cbe51dfb9b79441ff66 to your computer and use it in GitHub Desktop.
Save meinac/7cbe51dfb9b79441ff66 to your computer and use it in GitHub Desktop.
defmodule Meinac.User do
use Meinac.Web, :model
schema "users" do
field :first_name, :string
field :last_name, :string
field :email, :string
field :password_digest, :string
field :password, :string, virtual: true
timestamps
end
@required_fields ~w(first_name last_name email password_digest)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> generate_password_digest
|> validate_format(:email, ~r/@/)
|> unique_constraint(:email)
end
defp generate_password_digest(changeset) do
case changeset.params["password"] do
nil -> changeset
password ->
changeset
|> put_change(:password_digest, Comeonin.Bcrypt.hashpwsalt(password))
end
end
end
@meinac
Copy link
Author

meinac commented Mar 12, 2016

Example

alias Meinac.User

params    = %{ email: "mehmetemininac@gmail.com", first_name: "Mehmet Emin", last_name: "INAC", password: "123456" }
changeset = User.changeset(%User{}, params)
changeset.errors # => [password_digest: "can't be blank"]

as you see, it returns blank error for password_digest but it shouldn't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment