philomena/lib/philomena_web/controllers/topic/move_controller.ex

44 lines
1.2 KiB
Elixir
Raw Normal View History

2019-12-14 00:31:42 +01:00
defmodule PhilomenaWeb.Topic.MoveController do
import Plug.Conn
use PhilomenaWeb, :controller
alias Philomena.Topics.Topic
alias Philomena.Topics
alias Philomena.Repo
import Ecto.Query
plug :load_topic
2019-12-14 17:10:33 +01:00
plug PhilomenaWeb.CanaryMapPlug, create: :move
2019-12-14 00:31:42 +01:00
plug :authorize_resource, model: Topic, id_name: "topic_id", persisted: true
# intentionally blank
# todo: moving
2019-12-14 17:10:33 +01:00
def create(conn, %{"topic" => topic_params}) do
topic = conn.assigns.topic
2019-12-14 17:43:26 +01:00
target_forum_id = String.to_integer(topic_params["target_forum_id"])
case Topics.move_topic(topic, target_forum_id) do
{:ok, %{topic: topic}} ->
topic = Repo.preload(topic, :forum)
2019-12-14 17:10:33 +01:00
conn
|> put_flash(:info, "Topic successfully moved!")
2019-12-14 17:43:26 +01:00
|> redirect(to: Routes.forum_topic_path(conn, :show, topic.forum, topic))
2019-12-14 17:10:33 +01:00
{:error, _changeset} ->
2019-12-14 17:43:26 +01:00
topic = Repo.preload(topic, :forum)
2019-12-14 17:10:33 +01:00
conn
|> put_flash(:error, "Unable to move the topic!")
2019-12-14 17:43:26 +01:00
|> redirect(to: Routes.forum_topic_path(conn, :show, topic.forum, topic))
2019-12-14 17:10:33 +01:00
end
2019-12-14 00:31:42 +01:00
end
defp load_topic(conn, _opts) do
topic = Topic
|> where(forum_id: ^conn.params["forum_id"], slug: ^conn.params["topic_id"])
|> Repo.one()
Plug.Conn.assign(conn, :topic, topic)
end
end