philomena/lib/philomena_web/controllers/topic_controller.ex

41 lines
1.1 KiB
Elixir
Raw Normal View History

2019-10-06 23:31:48 +02:00
defmodule PhilomenaWeb.TopicController do
use PhilomenaWeb, :controller
alias Philomena.{Forums.Forum, Topics.Topic, Posts.Post}
alias Philomena.Repo
import Ecto.Query
plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true
2019-10-06 23:59:47 +02:00
def show(conn, %{"id" => slug}) do
forum = conn.assigns.forum
topic =
Topic
|> where(forum_id: ^forum.id, slug: ^slug, hidden_from_users: false)
|> preload(:user)
|> Repo.one()
conn = conn |> assign(:topic, topic)
2019-10-09 01:40:26 +02:00
%{page_number: page} = conn.assigns.pagination
2019-10-06 23:59:47 +02:00
2019-10-06 23:31:48 +02:00
posts =
Post
|> where(topic_id: ^conn.assigns.topic.id)
2019-10-09 01:37:14 +02:00
|> where([p], p.topic_position >= ^(25 * (page - 1)) and p.topic_position < ^(25 * page))
2019-10-07 00:06:22 +02:00
|> order_by(asc: :created_at)
2019-10-06 23:31:48 +02:00
|> preload([:user, topic: :forum])
2019-10-09 01:40:26 +02:00
|> Repo.all()
posts =
%Scrivener.Page{
entries: posts,
page_number: page,
page_size: 25,
total_entries: topic.post_count,
total_pages: div(topic.post_count + 25 - 1, 25)
}
2019-10-06 23:31:48 +02:00
render(conn, "show.html", posts: posts)
end
end