Skip to content

Instantly share code, notes, and snippets.

@shahryarjb
Created April 26, 2017 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahryarjb/1300b9c5c28301f5b9dae25ec9cc35e4 to your computer and use it in GitHub Desktop.
Save shahryarjb/1300b9c5c28301f5b9dae25ec9cc35e4 to your computer and use it in GitHub Desktop.
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