Cyclic module usage in my code Error? Exists


Currently, I am replicating this Blog Post tutorial. I seem to run into a compile error when I attempt to run mix phx.server It does exist I am not sure how to bypass the error.

This is the code I put into my post_controller.ex file if i remove it the app runs fine

  def show(conn, %{"id" => id}) do
    post =
      |> Posts.get_post!
      |> Repo.preload([:comments])
    changeset = Comment.changeset(%Comment{}, %{})
    render(conn, "show.html", post: post, changeset: changeset)

  def add_comment(conn, %{"comment" => comment_params, "post_id" => post_id}) do
    post =
      |> Posts.get_post!()
      |> Repo.preload([:comments])
    case Posts.add_comment(post_id, comment_params) do
      {:ok, _comment} ->
        |> put_flash(:info, "Added comment!")
        |> redirect(to: Routes.post_path(conn, :show, post))
      {:error, _error} ->
        |> put_flash(:error, "Oops! Couldn't add comment!")
        |> redirect(to: Routes.post_path(conn, :show, post))

Here is the compile error that I am receiving when I start the server
== Compilation error in file lib/blog_app_web/controllers/post_controller.ex == ** (CompileError) lib/blog_app_web/controllers/post_controller.ex:71: Comment.__struct__/1 is undefined, cannot expand struct Comment. Make sure the struct name is correct. If the struct name exists and is correct but it still cannot be found, you likely have cyclic module usage in your code

I push the file to a GitHub repo

You didn’t aliased Comment module. Maybe you meant Comments?

1 Like

I did in the post_controller.ex file I have this alias BlogApp.Comments

That’s not sufficient - you need alias BlogApp.Comments.Comment to refer to the struct as Comment (no s)

For instance, the similar alias needed for %Post on line 5:


Thank you I got the webpage to display, however, the only part that works is adding a Post. The comment posts won’t come up neither will the button to add the file. My show.html.heex file has the updated code to display it along with the app.css, any idea?