I'd like to have a unique field in an Ecto model. This field should contain a random string which I can generate easily (for example, see here). However, I would like to avoid to generate the string and check if it's already present in the database, as that would expose me to race conditions.
I'd like to have it retry insertion until a unique string is found. But how do I it? Should it be inside the changeset/2
function?
defmodule LetsPlan.Event do
use LetsPlan.Web, :model
schema "events" do
field :name, :string
field :from, Ecto.DateTime
field :to, Ecto.DateTime
field :slug, :string
timestamps
end
@required_fields ~w(from to)
@optional_fields ~w(slug)
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> unique_constraint(:slug)
end
end