Skip to content

Commit ee147be

Browse files
adds member function to category context
1 parent cc0b1f9 commit ee147be

File tree

3 files changed

+11
-5
lines changed

3 files changed

+11
-5
lines changed

lib/reddit/category.ex

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,9 @@ defmodule Reddit.Category do
22
@moduledoc """
33
The Category context.
44
"""
5+
import Ecto
56

6-
import Ecto.Query, warn: false
77
alias Reddit.Repo
8-
98
alias Reddit.Category.Community
109

1110
@doc """
@@ -107,4 +106,10 @@ defmodule Reddit.Category do
107106
Community.changeset(community, attrs)
108107
end
109108

109+
def members(community) do
110+
community
111+
|> assoc(:subscriptions)
112+
|> Repo.aggregate(:count, :user_id)
113+
end
114+
110115
end

lib/reddit_web/controllers/community_controller.ex

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,11 @@ defmodule RedditWeb.CommunityController do
3434
end
3535

3636
def show(conn, %{"name" => name}) do
37-
community = Repo.get_by(Community, name: name) |> Repo.preload(:subscriptions)
37+
community = Repo.get_by(Community, name: name)
38+
members = Category.members(community)
3839

3940
if community do
40-
render(conn, "show.html", community: community)
41+
render(conn, "show.html", community: community, members: members)
4142
else
4243
redirect(conn, to: "/")
4344
end

lib/reddit_web/templates/community/show.html.eex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
<div class="card p-3">
4141
<p class="h5">About this community</p>
4242
<p class="mt-2"><%= @community.summary %></p>
43-
<p><%= pluralize "member", length(@community.subscriptions) %></p>
43+
<p><%= pluralize "member", @members %></p>
4444
</div>
4545

4646
<div class="p-3">

0 commit comments

Comments
 (0)