Created
June 27, 2016 09:36
-
-
Save NikitaMelnikov/998e43013219cf0a29c4b3dfab684cfd to your computer and use it in GitHub Desktop.
This file contains 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 Sandbox.User do | |
use Sandbox.Web, :model | |
schema "users" do | |
field :first_name, :string | |
field :last_name, :string | |
timestamps | |
end | |
@required_fields ~w(first_name last_name) | |
@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) | |
|> validate_length(:first_name, min: 2) | |
|> validate_length(:last_name, max: 256) | |
end | |
end |
This file contains 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 Sandbox.UserController do | |
alias Sandbox.User | |
plug :scrub_params, "user" when action in [:create, :update] | |
def index(conn, _params) do | |
users = Repo.all(User) | |
render conn, "index.html", users: users | |
end | |
def new(conn, _params) do | |
changeset = User.changeset(%User{}) | |
render conn, "new.html", changeset: changeset | |
end | |
def create(conn, %{"user" => user_params}) do | |
changeset = User.changeset(%User{}, user_params) | |
case Repo.insert(changeset) do | |
{:ok, _user} -> | |
conn | |
|> put_flash(:info, "User created successfully") | |
|> redirect(to: user_path(conn, :index)) | |
{:error, changeset} -> | |
render conn, "new.html", changeset: changeset | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment