mobilizon.chapril.org-mobil.../lib/mobilizon/addresses/address.ex

79 lines
1.8 KiB
Elixir
Raw Normal View History

defmodule Mobilizon.Addresses.Address do
2019-09-08 03:05:30 +02:00
@moduledoc """
Represents an address for an event or a group.
"""
use Ecto.Schema
2019-09-08 03:05:30 +02:00
import Ecto.Changeset
2019-09-08 03:05:30 +02:00
alias Mobilizon.Addresses.Address
alias Mobilizon.Events.Event
2019-09-08 03:05:30 +02:00
@type t :: %__MODULE__{
country: String.t(),
locality: String.t(),
region: String.t(),
description: String.t(),
floor: String.t(),
geom: Geo.PostGIS.Geometry.t(),
postal_code: String.t(),
street: String.t(),
url: String.t(),
origin_id: String.t(),
events: [Event.t()]
}
@required_attrs [:url]
@optional_attrs [
:description,
:floor,
:geom,
:country,
:locality,
:region,
:postal_code,
:street,
:origin_id
]
2019-09-08 03:05:30 +02:00
@attrs @required_attrs ++ @optional_attrs
schema "addresses" do
field(:country, :string)
field(:locality, :string)
field(:region, :string)
field(:description, :string)
field(:floor, :string)
2018-08-24 12:31:41 +02:00
field(:geom, Geo.PostGIS.Geometry)
field(:postal_code, :string)
field(:street, :string)
field(:url, :string)
field(:origin_id, :string)
2019-09-08 03:05:30 +02:00
has_many(:events, Event, foreign_key: :physical_address_id)
timestamps()
end
@doc false
2019-09-08 03:05:30 +02:00
@spec changeset(t | Ecto.Changeset.t(), map) :: Ecto.Changeset.t()
def changeset(%Address{} = address, attrs) do
address
|> cast(attrs, @attrs)
|> set_url()
2019-09-08 03:05:30 +02:00
|> validate_required(@required_attrs)
end
2019-09-08 03:05:30 +02:00
@spec set_url(Ecto.Changeset.t()) :: Ecto.Changeset.t()
defp set_url(%Ecto.Changeset{changes: changes} = changeset) do
url =
2019-09-08 03:05:30 +02:00
Map.get(
changes,
:url,
"#{MobilizonWeb.Endpoint.url()}/address/#{Ecto.UUID.generate()}"
)
put_change(changeset, :url, url)
end
end