Skip to content

Instantly share code, notes, and snippets.

@janjiss
Created December 14, 2015 13:04
Show Gist options
  • Select an option

  • Save janjiss/fa290e202d1bf17376e2 to your computer and use it in GitHub Desktop.

Select an option

Save janjiss/fa290e202d1bf17376e2 to your computer and use it in GitHub Desktop.
defmodule ElixirStream.Entry do
use ElixirStream.Web, :model
use Ecto.Model.Callbacks
alias ElixirStream.User
before_insert :set_slug
schema "entries" do
field :email, :string
field :author_name, :string
field :title, :string
field :body, :string
field :slug, :string
belongs_to :user, User
timestamps
end
@optional_fields ~w(email author_name)
@required_fields ~w(title body)
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> validate_length(:title, min: 5)
|> validate_length(:body, min: 15)
|> validate_length(:body, max: 500)
end
def set_slug(changeset) do
slug = Ecto.Changeset.get_field(changeset, :title) |>
String.strip |> String.downcase |> String.replace(~r/([^a-z0-9])+/, "-")
change(changeset, %{slug: slug})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment