phoenixRealWorld/lib/phoenixRealWorld_web/live/article_live/show.ex
ReyoKatsu 03e1691fea
fin
2025-04-24 03:07:36 +09:00

81 lines
2.5 KiB
Elixir

defmodule PhoenixRealWorldWeb.ArticleLive.Show do
use PhoenixRealWorldWeb, :live_view
alias PhoenixRealWorld.Blogs
alias PhoenixRealWorld.Blogs.Comment #←追加
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def handle_params(%{"id" => id}, _, socket) do
#↓追加&変更
article = Blogs.get_article!(id)
%{live_action: action, current_user: user} = socket.assigns
# 編集モードで、ログインユーザーが記事の作者でない場合は、記事一覧にリダイレクト
if action == :edit && article.author_id != user.id do
{:noreply, push_navigate(socket, to: ~p"/articles/#{article}")}
# 編集モードで、ログインユーザーが記事の作者である場合は、記事を表示
else
changeset = Blogs.change_comment(%Comment{}) #←追加
{:noreply,
socket
|> assign(:page_title, page_title(socket.assigns.live_action))
|> assign(:article, article)
|> assign(:comment_form, to_form(changeset))} #←追加
end
end
@impl true
def handle_event("delete", _value, socket) do
%{article: article, current_user: user} = socket.assigns
if article.author_id != user.id do
{:noreply, socket}
else
{:ok, _} = Blogs.delete_article(article)
{:noreply, push_navigate(socket, to: ~p"/articles")}
end
end
#追加
@impl true
def handle_event("validate_comment", %{"comment" => comment_params}, socket) do
changeset =
%Comment{}
|> Blogs.change_comment(comment_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, :comment_form, to_form(changeset))}
end
#追加
@impl true
def handle_event("post_comment", %{"comment" => comment_params}, socket) do
comment_params =
comment_params
|> Map.put("article_id", socket.assigns.article.id)
|> Map.put("author_id", socket.assigns.current_user.id)
case Blogs.create_comment(comment_params) do
#コメントの作成に成功した場合
{:ok, _} ->
article = Blogs.get_article!(socket.assigns.article.id)
changeset = Blogs.change_comment(%Comment{})
{:noreply,
socket
|> assign(:article, article)
|> assign(:comment_form, to_form(changeset))
|> put_flash(:info, "Comment posted successfully")}
#コメントの作成に失敗した場合
_ ->
{:noreply, socket}
end
end
defp page_title(:show), do: "Show Article"
defp page_title(:edit), do: "Edit Article"
end