Created
April 26, 2017 22:28
-
-
Save shahryarjb/1300b9c5c28301f5b9dae25ec9cc35e4 to your computer and use it in GitHub Desktop.
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
defmodule Rsvp.Events do | |
use Ecto.Schema | |
import Ecto.Changeset | |
schema "events" do | |
field :title, :string | |
field :location, :string | |
field :date, Ecto.DateTime | |
field :description, :string | |
timestamps() | |
end | |
# @required_fields ~w(title location date)a | |
# @optional_fields ~w(description)a | |
@required_fields [:title,:location,:date] | |
@optional_fields [:description] | |
def changeset(event, params \\ %{}) do | |
event | |
|> cast(params, @required_fields ++ @optional_fields) | |
|> validate_required(@required_fields) | |
|> validate_change(:date, fn(s, x) -> must_be_future(s,x) end) | |
end | |
# validate_change(:date, &must_be_future/2) | |
defp must_be_future(_ , value) do | |
Ecto.DateTime.compare(value, Ecto.DateTime.utc) | |
|> get_error | |
end | |
defp get_error(comparison) when comparison == :lt do | |
[date: "cant be in the past"] | |
end | |
defp get_error(_), do: [] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment