Skip to content

Instantly share code, notes, and snippets.

@m3ta4a
Last active March 29, 2019 17:10
Show Gist options
  • Save m3ta4a/e8086c3b4a81ee871a46d60fe9657388 to your computer and use it in GitHub Desktop.
Save m3ta4a/e8086c3b4a81ee871a46d60fe9657388 to your computer and use it in GitHub Desktop.
Person.ex changeset
def changeset(person, attrs) do
attrs = if attrs["birthday"] do
bday = attrs["birthday"]
{year, _} = Integer.parse(bday["year"])
{month, _} = Integer.parse(bday["month"])
{day, _} = Integer.parse(bday["day"])
case Timex.parse("#{year}/#{month}/#{day}", "{YYYY}/{M}/{D}") do
{:ok, date} ->
age = Timex.diff(Timex.now, date, :years)
Map.put(attrs, "age", age)
{:error, msg} -> IO.puts msg
end
else
attrs
end
person
|> cast(attrs, [:name, :age, :birthday, :address])
|> validate_required([:name, :age, :birthday, :address])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment