Last active
February 28, 2019 02:33
-
-
Save freqn/69615ce259205694ce358eee72a8955b 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 Discuss.TopicController do | |
use Discuss.Web, :controller | |
alias Discuss.Topic | |
def index(conn, _params) do | |
topics = Repo.all(Topic) | |
render conn, "index.html", topics: topics | |
end | |
def new(conn, _params) do | |
changeset = Topic.changeset(%Topic{}, %{}) | |
render conn, "new.html", changeset: changeset | |
end | |
def create(conn, %{"topic" => topic}) do | |
changeset = Topic.changeset(%Topic{}, topic) | |
case Repo.insert(changeset) do | |
{:ok, topic} -> | |
conn | |
|> put_flash(:info, "#{topic.title} Created") | |
|> redirect(to: topic_path(conn, :index)) | |
{:error, changeset} -> | |
render conn, "new.html", changeset: changeset | |
end | |
end | |
def edit(conn, %{"id" => topic_id }) do | |
topic = Repo.get(Topic, topic_id) | |
changeset = Topic.changeset(topic) | |
render conn, "edit.html", changeset: changeset, topic: topic | |
end | |
def update(conn, %{"id" => topic_id, "topic" => topic}) do | |
old_topic = Repo.get(Topic, topic_id) | |
changeset = Topic.changeset(old_topic, topic) | |
case Repo.update(changeset) do | |
{:ok, topic} -> | |
conn | |
|> put_flash(:info, "Topic updated") | |
|> redirect(to: topic_path(conn, :index)) | |
{:error, changeset} -> | |
render conn, "edit.html", changeset: changeset, topic: old_topic | |
end | |
end | |
def delete(conn, %{"id" => topic_id}) do | |
Repo.get!(Topic, topic_id) |> Repo.delete! | |
conn | |
|> put_flash(:info, "Topic Deleted") | |
|> redirect(to: topic_path(conn, :index)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment