can't resist
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

46 lines
1013 B

defmodule Tags.Tag do
use Ecto.Schema
import Ecto.Changeset
alias Tags.{Tag, Slug}
@attrs [:name, :slug, :rules]
@derive {Jason.Encoder, only: [:name]}
schema "tags" do
field :name, :string
field :slug, Slug.Type
field :rules, :string
timestamps()
end
def changeset(tag \\ %Tag{}, attrs \\ %{}) do
tag
|> cast(attrs, @attrs)
|> validate_required([:name])
|> unique_constraint(:name)
|> Slug.maybe_generate_slug()
|> Slug.unique_constraint()
end
def insert_changeset(tag \\ %Tag{}, attrs \\ %{}) do
tag
|> cast(attrs, @attrs)
|> validate_required([:name])
|> unique_constraint(:name)
|> add_default_rule()
|> Slug.maybe_generate_slug()
|> Slug.unique_constraint()
end
def add_default_rule(changeset) do
case get_change(changeset, :rules) do
nil ->
name = get_change(changeset, :name)
put_change(changeset, :rules, "title::contains::#{name}")
_ ->
changeset
end
end
end