Created
June 6, 2020 15:48
-
-
Save aristotelesbr/67de5640da26bd8a1a6f9369550ec3eb to your computer and use it in GitHub Desktop.
Como renderizar dados associados
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 RecipeBox.CreateRecipe do | |
@moduledoc """ | |
Create a new Recipe | |
""" | |
import Ecto.Changeset | |
alias RecipeBox.{Recipe, Repo} | |
def run(params) do | |
%Recipe{} | |
|> cast(params, [:title, :description, :quantity_people, :difficulty_level, :meal_id]) | |
|> validate_required([:title, :description]) | |
|> Repo.insert() | |
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 RecipeBoxWeb.RecipeController do | |
use RecipeBoxWeb, :controller | |
def create(conn, params) do | |
case CreateRecipe.run(params) do | |
{:ok, recipe} -> | |
conn | |
|> put_status(201) | |
|> render("recipe.json", %{recipe: recipe}) | |
{:error, _} -> | |
conn | |
|> put_status(422) | |
|> json(%{status: "unprocessable entity"}) | |
end | |
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 RecipeBoxWeb.RecipeView do | |
use RecipeBoxWeb, :view | |
def render("recipe.json", %{recipe: recipe}) do | |
%{ | |
id: recipe.id, | |
title: recipe.title, | |
description: recipe.description, | |
difficulty_level: recipe.difficulty_level, | |
quantity_people: recipe.quantity_people, | |
meal: %{ | |
id: recipe.meal.id, | |
title: recipe.meal.title, | |
description: recipe.meal.description, | |
active: recipe.meal.active, | |
inserted_at: recipe.meal.inserted_at, | |
updated_at: recipe.meal.updated_at | |
} | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment