Last active
March 29, 2019 17:10
-
-
Save m3ta4a/e8086c3b4a81ee871a46d60fe9657388 to your computer and use it in GitHub Desktop.
Person.ex changeset
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
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