Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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