Created
December 14, 2015 13:04
-
-
Save janjiss/fa290e202d1bf17376e2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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