Search code examples
elixirphoenix-frameworkecto

Ecto Associations


So I'm creating a simple app where user can posts. I'm still learning elixir so please bear with me.

MODEL SCHEMA

  • User
  • Avatar
  • Post
  • Comment

My problem is associating the user in the comment schema.

user -> has_one -> avatar

user -> has_many -> post -> has_many -> comments (user?)

I'm confused on how will I associate the user to comments


Solution

  • Each schema is allowed to have multiple associations. So you will want something that looks similar to the following

    user

    • has_one avatar
    • has_many posts
    • has_many comments

    avatar

    • belongs_to user

    post

    • belongs_to user
    • has_many comments

    comment

    • belongs_to user
    • belongs_to post

    I believe this should cover what you are looking for.