Last active
January 8, 2016 23:09
-
-
Save terakilobyte/cecdd72acf71378bb403 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 Votio.Topic do | |
| use Votio.Web, :model | |
| schema "topics" do | |
| field :title, :string | |
| field :categories, :map | |
| field :voted_by, {:array, :id} | |
| timestamps | |
| end | |
| @required_fields ~w(title categories) | |
| @optional_fields ~w() | |
| @doc """ | |
| Creates a changeset based on the `model` and `params`. | |
| If no params are provided, an invalid changeset is returned | |
| with no validation performed. | |
| """ | |
| def changeset(model, params \\ :empty) do | |
| model | |
| |> cast(params, @required_fields, @optional_fields) | |
| |> unique_constraint(:title) | |
| |> validate_categories | |
| |> validate_length(:title, min: 5, message: "Your title must be at least 5 characters") | |
| end | |
| def validate_categories(%{model: %{categories: nil}} = changeset), do: add_error(changeset, :categories, "must have at least two categories") | |
| def validate_categories(%{model: %{categories: categories}} = changeset) when map_size(categories) < 2 do | |
| add_error(changeset, :categories, "must have at least two categories") | |
| end | |
| def validate_categories(changeset), do: changeset | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment