forked from code-corps/code-corps-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcategory_controller.ex
More file actions
59 lines (49 loc) · 1.78 KB
/
category_controller.ex
File metadata and controls
59 lines (49 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
defmodule CodeCorps.CategoryController do
use CodeCorps.Web, :controller
alias CodeCorps.Category
alias JaSerializer.Params
plug :load_and_authorize_resource, model: Category, only: [:create, :update]
def index(conn, _params) do
categories = Category |> Repo.all |> Repo.preload([:project_categories])
render(conn, "index.json-api", data: categories)
end
def create(conn, %{"data" => data = %{"type" => "category", "attributes" => _category_params}}) do
changeset = Category.create_changeset(%Category{}, Params.to_attributes(data))
case Repo.insert(changeset) do
{:ok, category} ->
category =
category
|> Repo.preload([:project_categories])
conn
|> put_status(:created)
|> put_resp_header("location", category_path(conn, :show, category))
|> render("show.json-api", data: category)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(CodeCorps.ChangesetView, "error.json-api", changeset: changeset)
end
end
def show(conn, %{"id" => id}) do
category =
Category
|> preload([:project_categories])
|> Repo.get!(id)
render(conn, "show.json-api", data: category)
end
def update(conn, %{"id" => id, "data" => data = %{"type" => "category", "attributes" => _category_params}}) do
changeset =
Category
|> preload([:project_categories])
|> Repo.get!(id)
|> Category.changeset(Params.to_attributes(data))
case Repo.update(changeset) do
{:ok, category} ->
render(conn, "show.json-api", data: category)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(CodeCorps.ChangesetView, "error.json-api", changeset: changeset)
end
end
end