Error on self referencing association for has_many relationship

I’ve got a schema for messages. I want to maintain parent and children relationships on messages so that I can display a message along with all of its replies.

I saw the ecto docs on Self Referencing Associations on Many-to-Many relationships, but this is just a One-to-Many relationship. So I’ve been following the advice from this post from @atimberlake, but I’m getting a Warning error and don’t understand why.

Here’s my schema:

defmodule Message do
  schema "messages" do
     field :type, :string
     field :body, :string

     belongs_to :parent, Message
     has_many :children, Message, foreign_key: :parent_id
  end
end

Below are the errors I get. Why is it saying Message doesn’t exist when it should be able to see itself?

warning: invalid association `parent` in schema MyApp.Message: associated schema Message does not exist
  lib/my_app/message.ex:1: MyApp.Message (module)

warning: invalid association `children` in schema MyApp.Message: associated schema Message does not exist
  lib/my_app/message.ex:1: MyApp.Message (module)

A module’s name is not automatically aliased inside its definition - either write alias __MODULE__ above the schema block, or spell out the module name explicitly (MyApp.Message based on that error message).

1 Like

Thank you! Everything compiles with no warnings now. Whew!