Hi, I’m a beginner in Elixir so I’d appreciate any help that I get - especially if thoroughly explained!
Context:
I have a parent table called posts
and a child table called log_post_comment
that has a Foreign key pointing to posts
’ primary key (See the Entity relation diagram here)
I want to export all information about the posts
table onto an Excel sheet (.xlsl). I managed to export the post’s id
, title
, and body
. However, I can’t seem to get hold of log_post_comment
.
Question
How do I get the log_post_comment
records that are connected to the current post? Right now it’s a one-to-one relationship, but will it be different if it’s a one-to-many relation?
Here is my code (lib/myapp_web/views/exports/post_view.ex
)
defmodule Sandbox.Exports.PostView do
use SandboxWeb, :view
alias Elixlsx.{Workbook, Sheet}
@header [
"ID",
"Title",
"Body",
"Number of comments"
]
def render("report.xlsx", %{posts: posts}) do
report_generator(posts)
|> Elixlsx.write_to_memory("report.xlsx")
|> elem(1)
|> elem(1)
end
def report_generator(posts) do
rows = posts |> Enum.map(&(row(&1)))
%Workbook{sheets: [%Sheet{name: "Posts", rows: [@header] ++ rows}]}
end
def row(post) do
[
post.id,
post.title,
post.body,
post.log_post_comment.numOfComments # <-- ERROR
]
end
end
Error Output:
** (exit) an exception was raised:
** (UndefinedFunctionError) function nil.numOfComments/0 is undefined
nil.numOfComments()
(sandbox) lib/sandbox_web/views/exports/post_view.ex:27: Sandbox.Exports.PostView.row/1
(elixir) lib/enum.ex:1336: Enum."-map/2-lists^map/1-0-"/2
(elixir) lib/enum.ex:1336: Enum."-map/2-lists^map/1-0-"/2
(sandbox) lib/sandbox_web/views/exports/post_view.ex:19: Sandbox.Exports.PostView.report_generator/1
(sandbox) lib/sandbox_web/views/exports/post_view.ex:13: Sandbox.Exports.PostView.render/2
(phoenix) lib/phoenix/view.ex:472: Phoenix.View.render_to_iodata/3
(phoenix) lib/phoenix/controller.ex:776: Phoenix.Controller.render_and_send/4
(sandbox) lib/sandbox_web/controllers/exports/post_controller.ex:1: Sandbox.Exports.PostController.action/2
(sandbox) lib/sandbox_web/controllers/exports/post_controller.ex:1: Sandbox.Exports.PostController.phoenix_controller_pipeline/2
(phoenix) lib/phoenix/router.ex:352: Phoenix.Router.__call__/2
(sandbox) lib/sandbox_web/endpoint.ex:1: SandboxWeb.Endpoint.plug_builder_call/2
(sandbox) lib/plug/debugger.ex:136: SandboxWeb.Endpoint."call (overridable 3)"/2
(sandbox) lib/sandbox_web/endpoint.ex:1: SandboxWeb.Endpoint.call/2
(phoenix) lib/phoenix/endpoint/cowboy2_handler.ex:65: Phoenix.Endpoint.Cowboy2Handler.init/4
(cowboy) d:/Documents/4elements/Phoenix-Sandbox/deps/cowboy/src/cowboy_handler.erl:37: :cowboy_handler.execute/2
(cowboy) d:/Documents/4elements/Phoenix-Sandbox/deps/cowboy/src/cowboy_stream_h.erl:306: :cowboy_stream_h.execute/3
(cowboy) d:/Documents/4elements/Phoenix-Sandbox/deps/cowboy/src/cowboy_stream_h.erl:295: :cowboy_stream_h.request_process/3
(stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3